我先在EF6中使用代码,但似乎不能使用延迟加载。急切加载工作正常。我有以下几个类:
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
。我怀疑这是导致问题的原因。
发布于 2014-02-26 14:08:08
我意识到问题在于Merchant类不满足代理生成的要求。具体来说,我需要添加一个受保护的无参数构造函数。我只有一个私人的。
https://stackoverflow.com/questions/22031536
复制相似问题