❔ Unique Constraint Failed EF core
Hi, i tried to add a new program bending with a userId but I've this following error and i do not understand why because in my database i didn't set unique value for the UserId even if it is an foreign key
19 Replies
should i add this in my User model ?
Are you using migrations?
yes
I believe it will be fixed if you make the foreign key id nullable. I assume you want to make the relation optional?
Right now
ProgramBendings
probably has a foreign key defined that is required. It is therefore required that it has a relation to User
ye but the fact was that the foreign key specified was correct but for no reason i can't assigned the same userId to different
ProgramBending
currently i try to redo the migrations to be sure nothing was missingAre you manually assigning the id? Is it possible to get the related user and storing the reference in the actual user class properly of
ProgramBending
?
Modern EF does not even need the foreign key specified, just the class. It will do the rest for younop i do not set the userid manually
are you sure ? cause to me if i set the entity in
programBending
for example, it will try to create a new User entity in the database am i wrond ?It will do that if EF is not tracking that user. If you added the user in EF, or you retrieved it from the database, it will be tracked.
Otherwise it creates a new one and tracks it
hum ok i wasn't aware of this thanks
EF has a whole change tracking system which is not really explained a lot
i still have the problem even with a nullable foreign key
Did you make a new migration? It should explicitly remove the "required" part
i did it and the fact is i didn't set
UserId
to be unique
here my classes :
oh i think i've understand, perhaps i've forgot to add the relation between user and programbending in OnModelCreating
EF should do that automatically
ok here was my problem i found it 😄
i prefere to do it myself to be sure there is no problem in the relation between my classes
Makes sense
modelBuilder.Entity<ProgramBending>()
.HasOne(p => p.User)
.WithMany()
.HasForeignKey(p => p.UserId)
.OnDelete(DeleteBehavior.NoAction);
here was the missing part 😄
thanks for your help i was able to found my problem 😁Did you know that this can also be achieved with an attribute? https://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx
DataAnnotations - ForeignKey Attribute in EF 7 & EF Core
Learn about the [ForeignKey] DataAnnotation attribute in EF 6 and EF Core Code-First approach.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.