实体关联刷新有问题。当我得到这样的实体时:
MyContext context = new MyContext();
Person myPerson = context.PersonSet.FirstOrDefault();
String myPersonName = myPerson.Name;
Address myPersonAddress = myPerson.Address;
我找到了一个人,他有一个名为 Address 的关联和一个名为 Name 的属性。如果我手动修改数据库中的数据,例如属性名称,我必须使用以下代码重新加载我的实体:
context.Entry(myPerson).Reload();
并且我有 Name 的新值。但如果我对 Address 做同样的事情,它就不起作用了。我认为这是因为 Address 是一个关联属性。我需要刷新它。
我怎样才能强制重新加载 Address 关联(以及 Person 类中的所有其他关联)?
编辑:
同样的情况,一个人可以有多个地址。
MyContext context = new MyContext();
Person myPerson = context.PersonSet.FirstOrDefault();
String myPersonName = myPerson.Name;
List<Address> myPersonAddresses = myPerson.Addresses;
在这种情况下,它不是引用:
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
但是一个集合:
context.Entry(myPerson).Collection(p => p.Addresses).Load();
// Address will be populated with old value and new value
我需要用它来工作:
context.Entry(myPerson).Collection(p => p.Addresses).CurrentValue.Clear();
context.Entry(myPerson).Collection(p => p.Addresses).Load();
但对我的所有导航属性执行此操作似乎不是一个好的解决方案!
最佳答案
如果您不使用延迟加载,则可以显式加载新的 Address
(因为您必须显式加载它(例如,使用 Include
),当您最初加载 Person
时):
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
如果使用延迟加载,则不需要第二个代码块。尽管如此,一旦您访问新的 myPerson.Address
的属性,您就会得到一个对数据库的新查询(就像您在上面的第二个代码块中有一个新查询一样),因为第一行将标记如果此人引用数据库中的新地址,则导航属性未加载。
此行为不取决于您是否在模型类中公开了外键。
似乎没有办法调用一些单一的魔法 Reload
方法,它会在一次调用中重新加载和更新整个对象图(类似于没有单一的 Include
以急切加载完整的对象图)。
关于c# - 重新加载实体和所有导航属性关联 - DbSet Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9081244/