延迟加载不工作的SaveChanges实体框架后 [英] Lazy Loading Not Working After SaveChanges Entity Framework

查看:205
本文介绍了延迟加载不工作的SaveChanges实体框架后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的功能,context.SaveChanges()之后,实体属性类型总是空。我刚刚从(先用数据库)使用的ObjectContext来的DbContext转换,并在更改前,它工作得很好,现在没有。是否有什么我失踪?

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?

我检查PropertyTypeID,它是正确写入和存​​在于数据库。所有的关系都是正确db和EDMX文件设置。生成的文件.TT显示属性类型的对象为虚。这是EF 5

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.

修改

我发现,如果我添加的SaveChanges()后,这行代码,它的工作原理。然而,这是不理想的,我怎么可以把它默认加载的实体?

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.

推荐答案

您需要创建的,而不是使用代理为了让懒加载工作:

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

这篇关于延迟加载不工作的SaveChanges实体框架后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆