导航属性应该是虚拟的 - 在 ef core 中不需要? [英] navigation property should be virtual - not required in ef core?

查看:42
本文介绍了导航属性应该是虚拟的 - 在 ef core 中不需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得在 EF 导航属性应该是虚拟的:

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并且不要将其视为虚拟的:

But I look at EF Core and don't see it as virtual:

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 中从未必需.仅当您需要延迟加载支持时才需要它.

virtual was never required in EF. It was needed only if you want lazy loading support.

由于 EF Core 尚不支持延迟加载,目前 virtual 没有特殊意义.当(以及如果)他们添加延迟加载支持时(有一个 计划)这样做).

Since Lazy loading is not yet supported by EF Core, currently virtual have no special meaning. It would when (and if) they add lazy loading support (there is a plan for doing so).

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

Update: Starting with EF Core 2.1, Lazy loading is now supported. But if you don't add Microsoft.EntityFrameworkCore.Proxies package and enable it via UseLazyLoadingProxies, the original answer still applies.

但是,如果您这样做,由于初始实施中缺少选择加入控制,事情完全改变了 - 它要求 所有您的导航属性虚拟.这对我来说没有意义,在它得到修复之前你最好不要使用它.如果您确实需要延迟加载,请使用替代 无代理的延迟加载 方法,在这种情况下,virtual 再次无关紧要.

However if you do so, the thing's totally changed due to the lack of the opt-in control in the initial implementation - it requires all your navigation properties to be virtual. Which makes no sense to me, you'd better not use that until it gets fixed. If you really need lazy loading, use the alternative Lazy loading without proxies approach, in which case again virtual doesn't matter.

这篇关于导航属性应该是虚拟的 - 在 ef core 中不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆