当我保存一个新的 ThingDependency 时,它会适当地显示持久化的值......也就是说:它有它的 Id,以及 From 和 To Id 值。
...但是关联的实体是空的,我无法访问它们,直到我处理数据上下文并重新实例化它......然后它就可以正常工作了。
我只能参考您问题的这一部分,这听起来像是(但我的解释可能完全错误)您正在做这样的事情:
int newThingDependencyId = 0;
using (var context = new MyContext())
{
ThingDependency newThingDependency = new ThingDependency();
newThingDependency.FromThingId = 1;
newThingDependency.ToThingId = 2;
context.ThingDependencies.Add(newThingDependency);
context.SaveChanges();
newThingDependencyId = newThingDependency.Id;
Thing fromThing1 = newThingDependency.FromThing;
Thing toThing1 = newThingDependency.ToThing;
}
using (var context = new MyContext())
{
ThingDependency newThingDependency = context.ThingDependencies
.Find(newThingDependencyId);
Thing fromThing2 = newThingDependency.FromThing;
Thing toThing2 = newThingDependency.ToThing;
}
在这里,您想知道为什么fromThing1
和toThing1
是null
但又不是fromThing2
,对吗?toThing2
null
如果是,那么您必须更换...
ThingDependency newThingDependency = new ThingDependency();
...经过...
ThingDependency newThingDependency = context.ThingDependencies.Create();
Create
将创建一个能够加载fromThing1
和toThing1
延迟加载的动态代理,而使用new
操作符创建的普通对象则不能。Find
(或任何 LINQ 查询Single
等)也将实例化一个代理,这就是在第二个上下文中访问导航属性有效的原因。所有这些都假设您的导航属性被标记为virtual
并且您没有明确禁用延迟加载。
(如果我对此完全错误,请在您Thing
的问题中提供一些代码片段,以显示您在做什么!)