【问题标题】:EF5 Code First: Newly created entities' related entities are not lazy loaded although a proxy is usedEF5 Code First:尽管使用了代理,但新创建的实体的相关实体不会延迟加载
【发布时间】:2012-12-13 11:03:15
【问题描述】:

考虑以下 sn-p:

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

干杯, 蒂姆

【问题讨论】:

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


    【解决方案1】:

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

    protected DbContext Context;
    protected IDbSet<T> DbSet;
    
    public Repository(DbContext context)
    {
         Context = context;
         DbSet = Context.Set<T>();
    
         Context.Configuration.LazyLoadingEnabled = true;
    }
    

    我希望这对您有所帮助。

    【讨论】:

    • 正如我在原始问题中提到的,在我的测试用例中确实启用了延迟加载。
    猜你喜欢
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多