【问题标题】:DBContext lazyloadingenabled set to true still loads related entities by defaultDBContextlazyloadingenabled 设置为 true 仍然默认加载相关实体
【发布时间】:2012-05-25 13:16:57
【问题描述】:

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

一个药物类别中包含一个药物身份对象列表。

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

如果我想包含要加载的相关实体,则该类的特定配置会设置 key 和 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,而实际上它不应该包含相关的 DrugIdentities。

context.Configuration.LazyLoadingEnabled = true;

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

drugs[0].DrugIdentities Count = 1

我希望 drug[0].DrugIdentities 等于 NULL,因为延迟加载设置为 true?

【问题讨论】:

  • 您似乎将延迟加载误认为与实际情况相反。延迟加载意味着当您访问导航属性时,您的数据会自动加载。与此相反,急切加载是当您为关系属性获取空值时,除非您明确(急切地)加载它们。

标签: c# entity-framework-4.1


【解决方案1】:

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

中的延迟、急切和显式加载相关数据

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

【讨论】:

  • LazyLoadingEnabled 设置为 true,因为我不希望它急切加载数据。正在发生的事情是它在不应该的时候急切地加载相关实体。
  • 你怎么知道它是急切加载?尝试检查导航属性的行为会触发延迟加载。如果要加载相关实体,则使用延迟加载时,您将看不到 null 导航属性。
  • 即使在查看对象时,不展开它的属性也会显示 DrugIdentities 属性的 Count = 1。仅查看已填充的顶级类是否仍会触发急切加载?
【解决方案2】:

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

测试通过了我的预期。第一个查询返回Drugs 对象和NULLDrugEntities。第二个查询返回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;

【讨论】:

  • 您的第一个说法不正确。您可以将 ProxyCreationEnabled 和 LazyLoadingEnabled 都设置为 true。为未来的 Google 员工更正此问题。
  • 设置 ProxyCreationEnabled = falseLazyLoadingEnabled = true 对我有用。
  • 抱歉,ProxyCreation 不必为 false 即可将 LazyLoadingEnabled 设置为 true。这些是独立的。
  • 它适用于.net核心吗?因为我在上下文对象中看不到配置属性!
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2021-03-17
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多