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

时间:2012-05-17 22:56:46

标签: c# entity-framework-4.1

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] .DrugIdentities Count = 1

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

3 个答案:

答案 0 :(得分:2)

要禁用延迟加载,请将LazyLoadingEnabled设置为false而不是true。请参阅

中的 Lazy,Eager和Explicit Loading of Related Data

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

答案 1 :(得分:1)

如果要设置ProxyCreationEnabled = false,则必须专门设置LazyLoadingEnabled = true

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

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;

答案 2 :(得分:0)

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

相关问题