C#EF code第一个虚拟的关键字,它有什么作用?有什么、第一个、关键字、作用

2023-09-03 00:47:04 作者:逍遥自在

声明导航属性时,到底为什么我们需要使用虚拟的关键字?据我所知,C首先框架$ C $使用它在某种程度上认识到,属性是一个导航属性​​,但我想知道怎么办。具体来说,我想知道它如何与MSDN文档虚的关键字,给出的说明:http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx

Why exactly do we need to use the "virtual" keyword when declaring a navigation property? I understand that the Code First framework uses it somehow to recognize that the property is a navigation property, but I'd like to know how. Specifically, I'd like to know how it relates to the description given in the MSDN documentation for the "virtual" keyword: http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx

推荐答案

在运行时,实体框架会为你什么叫做代理实体。这些实体是从实体类型派生的动态创建的对象类型

On runtime, Entity Framework will generate for you what's called proxy-entities. Those entities are objects of dynamically created types that derive from your entity types.

这使您可以使用您的实体为一个 POCO ,这是不相关的实体框架以任何方式一个简单的对象,因为它不会从继承EntityObject

This allows you to use your entities as a POCO, which is a simple object that is not related to Entity Framework in any way, as it doesn't inherit from EntityObject.

在运行时,从你的POCO动态创建的实体类型继承,并覆盖所有虚拟属性增加实体框架的东西,可以让懒加载的属性干将。

On runtime, the dynamically created entity type inherits from your POCO, and overrides all your virtual properties to add the Entity Framework stuff that allows lazy-loading in the properties getters.

延迟加载是一个复杂的过程,需要你的code,以了解如何将数据来自于数据库中。因为你不希望你的域类了解数据库和EF的东西,你从EF抽象的实体和添加虚拟属性,因此EF可以覆盖你的基地POCO并在运行时添加了数据库相关的东西。

Lazy loading is a complex process that requires your code to know about how the data comes from the database. As you don't want your domain classes to know about the database and the EF stuff, you abstract your entities from EF and add virtual properties, so EF can override your base POCO and add its DB-related stuff on runtime.

相同变更跟踪。