gpt4 book ai didi

c# - 如果我将延迟加载设置为 false(暂时),那么包含 "virtual"关键字或不包含它是否重要?

转载 作者:太空狗 更新时间:2023-10-30 01:19:26 31 4
gpt4 key购买 nike

据我了解,如果我想在我的 EF6 应用程序中使用延迟加载,我应该将我的关系编码为这样,最后两项标记为虚拟:

public class Test
{
public int TestId { get; set; }
public int ExamId { get; set; }
public string Title { get; set; }
public int Status { get; set; }
public System.DateTime CreatedDate { get; set; }
public virtual Exam Exam { get; set; }
public virtual ICollection<UserTest> UserTests { get; set; }
}

如果我不想使用延迟加载(目前)并且如果我将延迟加载配置设置为 false 那么如果我保留 virtual 关键字是否有任何性能考虑因素或者我应该像这样在没有关键字的情况下编写我的类?

public class Test
{
public int TestId { get; set; }
public int ExamId { get; set; }
public string Title { get; set; }
public int Status { get; set; }
public System.DateTime CreatedDate { get; set; }
public Exam Exam { get; set; }
public ICollection<UserTest> UserTests { get; set; }
}

我问这个问题的原因是我想通过保留 virtual 关键字来保持灵 active ,但前提是当我不使用延迟加载时这不会给我带来任何问题。

我阅读了以下内容

"if you use the virtual keyword on an ICollection/one-to-many relationship property, it will be lazy-loaded by default, whereas if you leave the virtual keyword out, it will be eager-loaded."

即使我设置了 DbContext.Configuration.LazyLoadingEnabled = false; 也是如此吗?

最佳答案

virtual 关键字使得派生类可以在运行时动态创建成为可能,它会覆盖标记为virtual 的属性为了注入(inject)一些数据访问代码(“代理”)。但是当您设置 LazyLoadingEnabled = false 时,您告诉 Entity Framework “不要使用延迟加载代理覆盖我的实体类”。在这种情况下,virtual 关键字没有任何作用。 (好吧,从 .NET CLR 的角度来看,我实际上无法说出实例化具有 virtual 属性或方法的对象的成本是多少。它可能有一些成本,但我敢肯定它几乎没有与实际访问数据库相比。)

因此,在我看来,您将属性标记为 virtual 以便将来可能延迟加载的方法很好。

顺便说一句:这 - 如果你离开 virtual 关键字,它将被预加载 - 是错误的。如果您禁用延迟加载 - 通过省略 virtual 关键字或通过设置 LazyLoadingEnable = false - 默认情况下您不会进行预加载。相反,您根本没有加载(导航属性)。必须使用 Include 或使用投影显式编码预加载。

顺便提一下:您也可以稍后在需要时添加 virtual 修饰符。您可以将其限制为特定实体。 EF 不认为这是会以某种方式触及数据库架构的模型更改。

关于c# - 如果我将延迟加载设置为 false(暂时),那么包含 "virtual"关键字或不包含它是否重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22744518/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com