C#EF代码第一个虚拟关键字,它做什么? [英] C# EF Code First virtual keyword, what does it do?

查看:599
本文介绍了C#EF代码第一个虚拟关键字,它做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在声明导航属性时需要使用virtual关键字?我明白,Code First框架以某种方式使用它来识别该属性是一个导航属性,但我想知道如何。具体来说,我想知道它与MSDN文档中关于virtual关键字的描述有何关系: http://msdn.microsoft.com/en-us/library/9fkccyh4(v = vs80).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

推荐答案

在运行时,Entity Framework将为您生成所谓的代理实体。这些实体是从您的实体类型派生的动态创建类型的对象。

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 ,这是一个与Entity Framework无关的简单对象,因为它不继承自 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继承,并覆盖所有虚拟属性,以添加允许在属性getter中进行延迟加载的Entity Framework内容。

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.

懒惰加载是一个复杂的过程,需要您的代码了解数据来自数据库。由于您不希望您的域类知道数据库和EF资料,您可以从EF抽象您的实体并添加虚拟属性,因此EF可以覆盖您的基本POCO并在运行时添加其与DB相关的东西。

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.

相同更改跟踪

这篇关于C#EF代码第一个虚拟关键字,它做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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