Good afternoon.

Made similar to the example of Many to many Generic update method EF 6

But in my case, the values ​​from the collection property are re-created in the "DB".

public void Update(T updateItem) { using (var databaseContext = new TelesystemContext()) { T foundDal = databaseContext.Set<T>().Find(updateItem.Id); var entry = databaseContext.Entry(foundDal); entry.CurrentValues.SetValues(updateItem); var collection = entry.Collection("Permissions"); collection.Load(); collection.CurrentValue = typeof(T).GetProperty("Permissions").GetValue(updateItem); databaseContext.SaveChanges(); } } 

Those. Permissions each time you save an updateItem object are created anew, and should simply be added to the table — a bunch of many-to-many.

  • The fact that the string literal "Permissions" is used is for test purposes only. In general, it will naturally be replaced by a parameter. - Alexander
  • one
    You have somehow written too hard. It was enough databaseContext.Entry(updateItem).State = EntityState.Modified; - Pavel Mayorov
  • This is a generic implementation. But still, elements of the Permissions collection are created in the database again. Those. have a state Added - Alexander
  • Alexander, what's the difference that there is for the implementation? The code given to you does the same as yours. And the answer I wrote to you below. - Pavel Mayorov
  • Quarrel, for some reason at first I saw only a comment. - Alexander

1 answer 1

Your problem is that the Permissions entities you add do not belong to the context - and as a result they are added to it. You need to explicitly go through these permissions - and indicate that they are in the Unchanged status:

 foreach (var p in updateItem.Permissions) databaseContext.Entry(p).State = EntityState.Unchanged; 

PS because the Permissions property is not directly accessible - you will have to figure out how to access it. I intentionally did not write code to get this property - because it is not related to the task.

  • Assigning EntityState.Unchanged also not correct. And if they really added. How to make a generic solution with disconnected entities? - Alexander
  • @Alexander, and you should think about how to track this. In general, the problem has no solution. - Pavel Mayorov