Lazy Loading Not Working After SaveChanges Entity

2020-07-15 01:12发布

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条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-15 01:50

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;
}
查看更多
登录 后发表回答