LazyLoadingEnabled为false但仍未加载

时间:2015-11-10 19:01:33

标签: entity-framework linq-to-sql ef-code-first lazy-loading

我的EF代码第一个数据模型中有以下内容:

public class B
{
   [Key]
   public int Id { get; set; } 
   ... some data ..
}

public class D: B
{
    public D() { RelatedData = new List<RelatedData>(); }
    public List<RelatedData> RelatedData { get; set; }
}

public class RelatedData
{
    [Key]
    public int Id { get; set; }
    public int DId { get; set; }
    ... some data ...
}

在数据库中,我将查找记录D,其中包含2条RelatedData记录。

我的访问例程通过基类获取数据。

B Lookup(int desiredId)
{
    ...
    using (MyDataContext db = new MyDataContext())
    {
        db.Configuration.LazyLoadingEnabled = false;

        B b = (from x in db.B
               where x.Id == desiredId
               select x).FirstOrDefault();

        // b is actually a type D; however, ReleatedData has no records.
        // If I serialize b and return it, ReleatedData is empty.

        // Running this silly code below when I am dealing with a type D
        // which really only hits the DB and throws away the data now forces
        // the related data in b to load.
        if ( b is  D)
        {
            var notUsed = (from r in db.RelatedData
                           where r.DId == desiredId
                           select r).ToList();

            // Serializing b now gives valid results.
        }
    }
}

}

为什么我必须完成检索相关数据的额外步骤?是否LazyLoadingEnabled = false强制在第一次查询期间加载所有相关数据?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

解决方案可以是首先使用OfType扩展方法仅与D实体一起使用,然后使用Include扩展方法来急切加载RelatedData导航属性。< / p>

var d= db.B.OfType<D>().Include(d=>d.RelatedData).FirstOrDefault(d=>d.Id == desiredId);

现在关于你的问题,你不需要额外的查询来加载相关的实体。如果再次启用延迟加载并将RelatedData属性声明为virtual,则在第一次查询后咨询该属性时,您将看到EF将加载该相关实体。如果您想查看POCO实体需要遵循的要求,请查看link

更新

好吧,正如我在评论中所说,也许你错过了一些不让延迟加载正常工作的东西。

另一个解决方案可能是load explicitly导航属性:

 D entity= b as D;
context.Entry(entity).Collection(p => p.RelatedData).Load();