This question has already been answered:

Good day everyone! With the help of EF, added the Users and Audios tables, the EF itself automatically generated the third table for the link:

public class User { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public List<Audio> Audios { get; set; } } public class Audio { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public string Artist { get; set; } public string Title { get; set; } public List<User> Users { get; set; } } 

When I try to add a user with a list of audio recordings, everything is fine, but when I try to add another user with audio recordings that the first user has, he throws out an error saying that it’s impossible to add the same audio. If I delete from the second user the audio that is already in the database, the connection will not be established. I thought to fill in the user and the missing audio separately, and then directly using the sql query to add to the link table, but this method seems to be crutch and incorrect. I hope for your help!

Reported as a duplicate by Pavel Mayorov , pavel , Mirdin , PashaPash members c # Sep. 29 '16 at 11:22 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • We need to look at the add code itself. Are .Include (a => a.Users) and .Include (u => u.Audios) used? There, EF has many aspects, but the simplest version of the implementation for some reason just works, rather than complex. - Krona battery
  • This question was asked here 100,500 times. Look for the keywords "Entity Framework," "add." - Pavel Mayorov
  • I personally did not find @PavelMayorov, I think from 100,500 you will offer at least 5 links? - Buka

1 answer 1

It was decided:

 db.Entry(user).State = EntityState.Modified; //цикл ниже гарантирует существование дочерних элементов(аудио) в таблице foreach (var userAudio in user.Audios) { db.Audios.AddOrUpdate(userAudio); } db.Users.AddOrUpdate(user); db.SaveChanges(); 
  • AddOrUpdate accurate with AddOrUpdate is a pretty buggy method. In particular, he will never tell you whether he actually did the Add or Update. - Pavel Mayorov
  • And it certainly does not make any sense to do db.Users.AddOrUpdate(user); after the line db.Entry(user).State = EntityState.Modified; ! - Pavel Mayorov
  • @PavelMayorov that is, I leave only Add? - Buka
  • @Buka db.Entry (user) .State = EntityState.Modified does the same thing as db.Users.AddOrUpdate (user). They are mutually exclusive, so in this case you did an extra step - Valeriy Posvistak
  • @ValeriyPosvistak, the practice above showed that this parameter indicates that the dependent entity was also changed, and it was thanks to him that I got rid of the error - Buka