1

考虑以下代码段:

// 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 并且属性是虚拟的,并且在更改状态时,神奇地开始工作?如果我没记错的话,即使对于瞬态对象,延迟加载也应该有效,不是吗?

干杯,蒂姆

4

1 回答 1

0

似乎在实体框架 5 中默认禁用延迟加载功能,我在 web 上发现没有任何用处,但在定义“DbContext”对象后,我发现了在代码中明确设置此功能的问题:

protected DbContext Context;
protected IDbSet<T> DbSet;

public Repository(DbContext context)
{
     Context = context;
     DbSet = Context.Set<T>();

     Context.Configuration.LazyLoadingEnabled = true;
}

我希望这能够帮到你。

于 2013-01-28T13:02:57.897 回答