I have a problem with entity association refresh. When I get an entity with like this:
MyContext context = new MyContext();
Person myPerson = context.PersonSet.FirstOrDefault();
String myPersonName = myPerson.Name;
Address myPersonAddress = myPerson.Address;
I got an a person with an association named Address and a property named Name. If I modify manually the datas in database for example the property Name, I have to use the following code to reload my entity:
context.Entry(myPerson).Reload();
and I have the new value for Name. But If I do the same for Address it doesn't work. I think it is because Address is an association property. I need to refresh it.
How Can I do to force the reload of Address association (and all other association in Person class) ?
EDIT:
In the same case, a person can have more than one address.
MyContext context = new MyContext();
Person myPerson = context.PersonSet.FirstOrDefault();
String myPersonName = myPerson.Name;
List<Address> myPersonAddresses = myPerson.Addresses;
In this case, it is not a Reference:
context.Entry(myPerson).Reference(p => p.Address).Load();
// Address will be populated with only the new address
// this isn't required because I use lazy loading
but a Collection:
context.Entry(myPerson).Collection(p => p.Addresses).Load();
// Address will be populated with old value and new value
I need to use this to work:
context.Entry(myPerson).Collection(p => p.Addresses).CurrentValue.Clear();
context.Entry(myPerson).Collection(p => p.Addresses).Load();
But it doesn't seem to be a good solution to do this for all my navigation properties!
context.Entry(myPersonAddress).Reload()
does not work? – MidgetAddress
entity but the relationship to possibly anotherAddress
entity. Hm, good question... – MidgetPerson
have an exposed foreign key property for theAddress
navigation property? – MidgetAddress
, something likepublic int AddressId { get; set; }
in yourPerson
class. – Midget