2014-02-26 32 views
19

我先用EF6代码,但似乎无法得到惰性加载工作。急切的加载工作正常。我有以下类:EF代码第一懒惰加载不工作

public class Merchant : User 
{ 
    ... 

    public virtual ICollection<MerchantLocation> MerchantLocations { get; set; } 
} 

public class MerchantLocation : BaseEntity 
{ 
    ... 

    public int MerchantId { get; set; } 
    public virtual Merchant Merchant { get; set; }  
} 

public class User : BaseEntity 
{ 
    ... 
} 

public class BaseEntity 
{ 
    ... 

    public int Id { get; set; } 
} 

我通过下面的代码测试我的位置的延迟加载(这失败):

public void Test_Lazy_Loading() { 
    using (var context = new MyDbContext()) { 
     var merchant = context.Users.OfType<Merchant>.First(); 
     merchant.MerchantLocations.ShouldNotBeNull(); // fails 
    } 
} 

但是预先加载正常工作:

public void Test_Eager_Loading() { 
    using (var context = new MyDbContext()) { 
     var merchant = context.Users.OfType<Merchant>.Include("MerchantLocations").First(); 
     merchant.MerchantLocations.ShouldNotBeNull(); // passes 
    } 
} 

MerchantLocations被标记为public virtual,所以我不确定是什么问题。我还添加在我DbContext构造如下:

Configuration.LazyLoadingEnabled = true; 
Configuration.ProxyCreationEnabled = true; 

编辑:我也注意到,在返回上述试验的merchant对象不是一个EF代理。这是一个普通的Merchant。我怀疑这是造成这个问题的原因。

+1

不回答你的问题,但它的糟糕的设计使用基础实体类,http://msdn.microsoft.com/en-us/magazine/jj553510.aspx –

+0

我猜这可能是因为你使用OFType ,你怎么不直接从上下文访问商家,而是通过用户浏览 –

+0

我看到了作者对基本实体类的看法,但EF中的默认设置实际上将这些属性映射到派生表中,而不是一个单独的BaseEntity表,因此性能不受影响。我并不认为他的概念论证很强大,我需要一些像DateAdded和DateUpdated这样的更改跟踪信息,所以基类使这更容易 – user1032657

回答

43

我意识到问题在于商家类不符合代理生成的要求。具体来说,我需要添加一个受保护的无参数构造函数。我只有一个私人的。

+8

你救了我的命。 – Gh61

+4

也一样!另一个生命保存:) –

+0

谢谢我花了2小时在这 –