EF6延迟加载不适用于导航属性 [英] EF6 Lazy Loading not working for a navigation property

查看:115
本文介绍了EF6延迟加载不适用于导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在其他可以正常运行的应用中,我有2个新实体,我修剪了不相关的属性(所有内容均标记为虚拟):

I've got 2 new entities in an otherwise working app, I've trimmed unrelated properties (everything is marked virtual):

QuoteOverrideRequest

QuoteOverrideRequest

public virtual int RequestedById { get; set; }
public virtual int QuoteId { get; set; }
public virtual int StatusId { get; set; }

//nav properties
public virtual Customer RequestedBy { get; set; }
public virtual Quote Quote { get; set; }
public virtual QuoteOverrideRequestStatus Status { get; set; }

所有3个导航属性都以相同的方式映射。当我创建一个新的QuoteOverrideRequest并将其插入时,RequestedBy和Quote会自动填充其实体。状态不是。

All 3 navigation properties are mapped the same way. When I create a new QuoteOverrideRequest and insert it, RequestedBy and Quote are auto populated with their entities. Status is not.

QuoteOverrideRequest request = new QuoteOverrideRequest();
request.QuoteId = quoteId;
request.RequestedById = _workContext.CurrentCustomer.Id;
request.StatusId = 1;

_quoteService.InsertOverrideRequest(request);

insert函数正在调用存储库,该存储库将对象添加到DbSet并调用DbContext.SaveChanges(

The insert function is calling a Repository that adds the object to a DbSet and calls the DbContext.SaveChanges()

我认为问题出在QuoteOverrideRequestStatus上,因为其他2个类正确地延迟加载了。如果我在函数中较早地获得了该Status的实例,它将在插入后显示在Status属性中。

I assume the problem is with QuoteOverrideRequestStatus because the other 2 classes lazy load correctly. If I get an instance of that Status earlier in the function, it will show up in the Status property after the insert.

QuoteOverrideRequestStatus类具有公共的无参数构造函数,并且其所有属性都是虚拟的。

The QuoteOverrideRequestStatus class has a public parameterless constructor and all of it's properties are virtual.

public partial class QuoteOverrideRequestStatus : BaseEntity
{
    public QuoteOverrideRequestStatus() { }

    public virtual string Name { get; set; }
    public virtual int DisplayOrder { get; set; }
}

BaseEntity具有Id属性。我已经确认,在所有这些运行时,延迟加载和代理生成在DbContext上都是正确的。

BaseEntity has the Id property. I've confirmed that Lazy Loading and Proxy Generation are both true on the DbContext when all this runs.

推荐答案

new QuoteOverrideRequest()

这是不正确的。延迟加载不适用于使用 new 关键字实例化的模型的属性。

This is not correct. Lazy loading won't work for properties of models you instantiate using the new keyword.

您应使用 db.Set< T>()。Create()其中 db 是您的 DbContext T 是您的模型。

You should use db.Set<T>().Create() where db is your instance of DbContext and T is your model.

这将实例化模型的正确代理对象这将启用延迟加载导航属性。

This will instantiate the correct proxy object of your model which will enable lazy-loading navigation properties.

这篇关于EF6延迟加载不适用于导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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