Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Loading Not Working After SaveChanges Entity Framework

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.

like image 219
Ricketts Avatar asked Dec 04 '12 20:12

Ricketts


1 Answers

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;
}
like image 133
Slauma Avatar answered Oct 24 '22 17:10

Slauma