c# - 导航属性应该是虚拟的 - 在 ef 核心中不需要吗?

标签 c# entity-framework virtual entity-framework-core navigation-properties

我记得在 EF navigation property should be virtual :

public class Blog 
{  
    public int BlogId { get; set; }  
    public string Name { get; set; }  
    public string Url { get; set; }  
    public string Tags { get; set; }  

    public virtual ICollection<Post> Posts { get; set; }  
}

但我看EF Core不要将其视为虚拟:

public class Student
    {
        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }

        public ICollection<Enrollment> Enrollments { get; set; }
    }

是不是不需要了?

最佳答案

virtual 在 EF 中从来都不是必需的。仅当您需要延迟加载支持时才需要它。

Lazy loading is not yet supported by EF Core ,目前 virtual 没有特殊含义。它会在(如果)他们添加延迟加载支持(有一个 plan 用于这样做)。

更新:从 EF Core 2.1 开始,Lazy loading现在支持。但是如果你不添加 Microsoft.EntityFrameworkCore.Proxies通过UseLazyLoadingProxies打包并启用它,原来的答案仍然适用。

但是,如果您这样做,由于在初始实现中缺少选择加入控件,事情就完全改变了 - 它需要 所有您的导航属性虚拟。这对我来说毫无意义,在它得到修复之前你最好不要使用它。如果您确实需要延迟加载,请使用替代方案 Lazy loading without proxies方法,在这种情况下 virtual 也不重要。

关于c# - 导航属性应该是虚拟的 - 在 ef 核心中不需要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41881169/

相关文章:

c - 如何等待时间到期

c# - 如何在 C# 中将 Textfield 值插入数据库,代码如下

c# - 与打开 FileStream 相关的异常问题

database - Entity Framework : how to create double relationship (1-1 and many-1) with same objects

c# - ServiceProvider 不为 transient EF 上下文释放内存

c# - .Net Core 中的 DbContextTransaction 在哪里

c++ - 实现自定义 Gtkmm 小部件 : what should I return in the virtual on_* functions?

C#如何判断一个日期是否在距现在180天以内

c# - HTTP 请求未经授权,客户端身份验证方案为 'Ntlm' 从服务器收到的身份验证 header 为 'NTLM'

C#:虚函数调用甚至比委托(delegate)调用更快?