I have a problem with entity association refresh. When I get an entity with like this:
MyContext context = new MyContext();
Person myPerson = context.Person
Thank you !
context.Entry(myPerson).Collection(p => p.Addresses).Load();
did its job for me.
If p.Addresses lost one entry, it can be refreshed by
((IObjectContextAdapter)CurrentContext(context)).ObjectContext.Refresh(RefreshMode.StoreWins, p.Addresses);
but if it gained one entry, only your .Load() method helped. Thanks again!
I've solved this problem with using Detach before reading object from dbContext. This method allowed me to refresh all navigation properties of the object. I've described my scenario and details of solution here Entity Framework: Reload newly created object / Reload navigation properties
You need to use Query() extension to modify your LINQ expression. Here it is an example on basis of my personcal code. In this code I reload Addresses collection with related AddressType navigation property for myPerson object and place the result into SomeList:
_DbContext.Entry<Person>(myPerson)
.Collection(i => i.Adresses) // navigation property for Person
.Query()
.Include("AddressType") // navigation property for Address
.OrderBy(i => i.Name)
.ThenBy(i => i.AddressType.AddressTypeName) // just an example
.Select(i => new someClass
{
SoomeField1 = i.SomeField1,
...
})
.ToList()
.ForEach(i => SomeList.Add(i)); // SomeList is a List<T>
If you don't use lazy loading, you have the load the new Address
explicitly (as you had to load it explicitly (with Include
, for example), when you loaded the Person
initially):
context.Entry(myPerson).Reload();
// If the person refers to another Address in the DB
// myPerson.Address will be null now
if (myPerson.Address == null)
context.Entry(myPerson).Reference(p => p.Address).Load();
// myPerson.Address will be populated with the new Address now
If you use lazy loading, you don't need the second code block. Nonetheless, you get a new query to the database as soon as you access properties of the new myPerson.Address
(like you have a new query in the second code block above) because the first line will mark the navigation property as not loaded if the person refers to a new address in the DB.
This behaviour doesn't depend on whether you have exposed the foreign key in the model class or not.
There doesn't seem to be a way to call some single magic Reload
method which would reload and update the whole object graph in one call (similar like there is no single Include
to eager load a complete object graph).