简体   繁体   中英

C# EF 6.0 - Update Navigation Property Collections on objects added to context collections

Navigation property collections (possibly all navigation properties) are not updated when adding objects to the context table collections.

EG

Class A has a collection of Class B's. A new B is added to the context.B's collection, where it should be retrievable from the AB's collection based on the key values provided. It can be retrieved from the context.B's collection directly, but it does not get added to the AB's collection properly when context.SaveChanges() is called (this is the crux of the issue).

What bit of configuration is missing that will trigger the update of the AB's collection anytime a new object is added do the context.B's collection? Documentation leads me to believe that it should all 'just work' as soon as SaveChanges() is called, but it most definitely is not .

Currently, anytime I add a new object to a context collection, I have to also manually add it to the navigation property collections of other entities where it should be accessible automatically. This makes an absolute mess out of what should be simple code, and leads me to believe either I'm doing something wrong with the setup, or there is a major bug in the EF that I'm using.

Buried in the comments of another similar question, was the gem I was looking for that forces reloading of navigation property collections.

Refresh entity framework collection property

stackoverflow.com/questions/9081244/… use
context.Entry(myPerson).Collection(p => p.Addresses).CurrentValue.Clear(); and
context.Entry(myPerson).Collection(p => p.Addresses).Load();

The last bit is the important functional piece that I needed:

context.Entry(myPerson).Collection(p => p.Addresses).Load();

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