考虑以下代码段:
// this.ctx is an instance of our EF Code First DB Context.
// the entity in this example is called "Something", and the DB set "Somethings".
// there is also another entity type called "SomethingElse".
// the Something entity is declared like this:
//
// public class Something {
// public int Foo { get; set; }
// public string Bar { get; set; }
//
// public virtual IList<SomethingElse> RelatedStuff { get; set; }
// }
//
// Create is used to ensure a proxy is created.
var something = this.ctx.Somethings.Create();
// The new entity is added
this.ctx.Somethings.Add(something);
// lazy loading: ON
System.Diagnostics.Debug.Assert(this.ctx.Configuration.LazyLoadingEnabled);
// the entity is really in "added" state
System.Diagnostics.Debug.Assert(this.ctx.Entry(something).State == EntityState.Added);
// *** lazy loading does not work! ***
System.Diagnostics.Debug.Assert(something.RelatedStuff == null);
// note: if stepping through this with the debugger, I can confirm that "something" is
// of the DynamicProxy type, not a plain "Something" POCO.
// but, if we change the state manually...
this.ctx.Entry(something).State = EntityState.Unchanged;
// *** it works!! *** (doing a this.ctx.SaveChanges(), actually, also makes this work)
System.Diagnostics.Debug.Assert(something.RelatedStuff!= null);
有人可以向我解释为什么新创建的 POCO 上的延迟加载不起作用,虽然延迟加载是 ON 并且属性是虚拟的,并且在更改状态时,神奇地开始工作?如果我没记错的话,即使对于瞬态对象,延迟加载也应该有效,不是吗?
干杯,蒂姆