繁体   English   中英

DBContext lazyloadingenabled设置为true仍默认加载相关实体

[英]DBContext lazyloadingenabled set to true still loads related entities by default

LazyLoadingEnabled专门设置为true以防止相关实体在我正在使用的上下文中加载。

药物类别中有药物相关对象列表。

public class Drug
{
   public virtual List<DrugIdentity> DrugIdentities { get; set; }
}

如果我想要包含要加载的相关实体,则该类的特定配置设置密钥和hasmany关系。

public DrugConfiguration()
    {
        this.HasKey(d => d.DrugID);
        this.HasMany(d => d.DrugIdentities).WithOptional(d => d.Drug).Map(d => d.MapKey("DrugID"));
    }

当使用linq查询加载Drug上下文时,对象显示它不包含相关的DrugIdentities。

context.Configuration.LazyLoadingEnabled = true;

                    var drugs = from d in context.Drug
                                where d.Active == true
                                select d;

药物[0]。药物身份数= 1

我认为药物[0] .DrugIdentities等于NULL,因为lazyloading设置为true?

要禁用延迟加载,请将LazyLoadingEnabled设置为false而不是true。 请参阅Lazy,Eager和Explicit Loading of Related Data in

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-应用

你必须专门设置ProxyCreationEnabled = false ,如果你想设置LazyLoadingEnabled = true

测试通过了我的预期。 第一个查询返回Drugs对象,而DrugEntities返回NULL 第二个查询返回DrugEntities因为我使用Include进行DrugEntities加载。

var queryDrug = from d in context.Drug
                                where d.Active == true
                                select d;

                var drugresults = from d in context.Drug.Include(e => e.DrugIdentities)
                                  where d.Active == true
                                  select d;

这是延迟加载的行为。 如果你只是使用药物的属性,那么就不会有任何sql来查询DrugIdentities。 如果您使用DrugIdentities甚至只是在调试窗口中观察它,那么将有sql查询DrugIdentities和每种药物与单个DrugIdentities搜索查询。 您可以通过查看SQL事件探查器捕获的SQL来证明该行为。 如果您在查询药物时希望DrugIdentities为null,您可以通过删除DrugIdentities之前的虚拟关键词来更改模型。 然后当您查询药物时,DrugIdentities将保持为空,直到您通过另一个查询将DrugIdentities加载到上下文。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM