Reputation: 650
I have three small model classes and although two of them does works one is not and I can't figure out why. I found several solutions but neither of them helped me. First of all, code first approach was used in the project.
So, the main problem is that the PK in the Coupon
class is not set to autoincrement value. I refer to the tables from Server Explorer and see PK's properties. Realized that other two classes PK's properties are set as Is Identity
to True
and Identity Increment = 1
whereas in the Coupon
's PK's property they are set as Is Identity
to False
and Identity Increment
to 0.
I think the problem is somewhere there and below you can find the small model class I am having trouble with.
public class Coupon
{
public Coupon()
{
footballMatches = new List<FootballMatch>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CouponId { get; set; }
public int UserId { get; set; }
public virtual List<FootballMatch> footballMatches { get; set; }
}
Ask me more if you need further information.
Thanks !
Upvotes: 1
Views: 5659
Reputation: 650
Not expected that, but I found the solution in such a silly way. The solution to my problem was just re-adding the key. At first, I did not agree with marc_s because I also tried re-adding before. Apparently, I did in a wrong way when I firstly tried re-adding.
What I made wrong is converting int
to string
then converting back to int
while I did not touch the name of the instance, which is CouponId. That did not work. However, and sadly, I also had to change the name of the instance as well to make it work. I changed the line public int CouponId
to public string CouponName
then convert back to the actual name. Now it shows the expected behaviour.
Briefly, the simple solution is to change the key both variable and name and alter them to their actual names again. That simply.
By the way, while doing them please do not forget to update your migrations between each step. So the workflow is like Change->Update->Change Back->Update.
Hope that can help others who went through the same trouble.
Upvotes: 1