简体   繁体   中英

C# EF Code First virtual keyword, what does it do?

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 .

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 .

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.

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.

Same for change tracking .

添加virtual允许EF生成一个派生类,该类覆盖该属性并从数据库返回一个集合。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM