首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >EF Code First延迟加载不起作用

EF Code First延迟加载不起作用
EN

Stack Overflow用户
提问于 2014-02-26 12:07:20
回答 1查看 15.4K关注 0票数 29

我先在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。我怀疑这是导致问题的原因。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-26 14:08:08

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

票数 58
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22031536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档