EF5代码优先:尽管使用了代理,但新创建的实体的相关实体不是延迟加载的

时间:2012-12-13 11:03:16

标签: entity-framework lazy-loading code-first poco

请考虑以下代码段:

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

干杯,    添

1 个答案:

答案 0 :(得分:0)

似乎在实体框架5中默认禁用了延迟加载功能, 我在网上找不到任何有用的东西,但在定义“DbContext”对象后,在代码中明确地设置了这个功能,我发现了我的问题:

protected DbContext Context;
protected IDbSet<T> DbSet;

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

     Context.Configuration.LazyLoadingEnabled = true;
}

我希望这会帮助你。