Lazy Loading Not Working After SaveChanges Entity Framework

人走茶凉 提交于 2019-12-12 08:54:03

问题


In the function below, after the context.SaveChanges(), the entity PropertyType is always null. I just converted from using ObjectContext to DBContext (with database first) and before the change, it worked fine and now it doesn't. Is there something I'm missing?

I check the PropertyTypeID and it is written correctly and exists in the db. All relationships are correctly setup in the db and edmx file. The generated .tt files show the PropertyType object as virtual. This is 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. 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.


回答1:


You need to create a proxy instead of using new in order to enable lazy loading to work:

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;
}


来源:https://stackoverflow.com/questions/13711065/lazy-loading-not-working-after-savechanges-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!