简体   繁体   中英

c# Entity framework updating of linked objects only when changed

In the Entity Framework for C#, if I have a POCO class that has a relationship with another class - eg Product and ProductCategory, so that each Product must have a category column ID that exists in the Category table, I can construct the POCO class with the relationship fine, and call repository.save. At this point it creates both the category and the product rows in the DB if they dno't exist.

If I try and then insert a new second product that has the same category object, then it tries to save both the product and the category again, and it complains that 0 rows are updated, as I have [ConcurrencyCheck] attribute on the classes.

I want it to behave so that if I save a second product and the linked category object already exists and hasn't changed, it will just not update it but still save the product.

is this possible?

Eg

Category c = new Category();
Product p1 = new Product { Category = c };
repository.Insert(p1);
repository.Save();

Product p2 = new Product { Category = c };
repository.Insert(p2);
repository.Save();

First question is it is disconnected graphs then you have to write according to scenario.

   DbSet.Add() will try to add all

   DbSet.Attach() will make sure context is aware of objects but state of elements will be unchanged.

   Context.Entry(entity).State=EntityState is how you can say what has been modified, added or deleted.

I hope this helps.

Source: (PluralSight, Julie Lerman, EF in Enterprise)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM