简体   繁体   English

SaveChanges实体框架后延迟加载不起作用

[英]Lazy Loading Not Working After SaveChanges Entity Framework

In the function below, after the context.SaveChanges(), the entity PropertyType is always null. 在下面的函数中,在context.SaveChanges()之后,实体PropertyType始终为null。 I just converted from using ObjectContext to DBContext (with database first) and before the change, it worked fine and now it doesn't. 我刚刚使用ObjectContext转换为DBContext(首先是数据库),在更改之前,它工作正常,现在却没有。 Is there something I'm missing? 有什么我想念的吗?

I check the PropertyTypeID and it is written correctly and exists in the db. 我检查PropertyTypeID并且它被正确写入并存在于db中。 All relationships are correctly setup in the db and edmx file. 所有关系都在db和edmx文件中正确设置。 The generated .tt files show the PropertyType object as virtual. 生成的.tt文件将PropertyType对象显示为虚拟对象。 This is EF 5. 这是EF 5。

Here is the code (non-important assignments of entity properties has been removed): 这是代码(实体属性的非重要分配已被删除):

    private ListingTransferDetail BeginListingTransferDetailReport(int PropertyTypeID)
    {
        ListingTransferDetail transfer_detail = new ListingTransferDetail();
        transfer_detail.PropertyTypeID = PropertyTypeID;

        using (IDXEntities context = new IDXEntities())
        {
            context.ListingTransferDetails.Add(transfer_detail);
            context.SaveChanges();
            TransferProgress += "<br /><br /><strong>" + DateTime.Now + "</strong>: Transfer initialized for property type \"" + transfer_detail.PropertyType.DisplayName + "\".";
        }

        return transfer_detail;
    }

Thanks in advance. 提前致谢。

EDIT 编辑

I have found that if I add this line of code after SaveChanges(), it works. 我发现如果我在SaveChanges()之后添加这行代码,它就可以了。 However, this is not ideal, how can I make it load the entity by default? 但是,这并不理想,我怎样才能使它默认加载实体?

context.Entry(transfer_detail).Reference(a => a.PropertyType).Load();

Thanks again. 再次感谢。

You need to create a proxy instead of using new in order to enable lazy loading to work: 您需要创建代理而不是使用new来启用延迟加载:

private ListingTransferDetail BeginListingTransferDetailReport(int PropertyTypeID)
{
    using (IDXEntities context = new IDXEntities())
    {
        ListingTransferDetail transfer_detail =
            context.ListingTransferDetails.Create();
        transfer_detail.PropertyTypeID = PropertyTypeID;

        context.ListingTransferDetails.Add(transfer_detail);
        context.SaveChanges();

        //...

        // the following triggers lazy loading of PropertyType now
        var something = transfer_detail.PropertyType.SomeProperty;
    }

    return transfer_detail;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM