Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 527
nckbrzg Avatar asked Jan 14 '13 15:01

nckbrzg


Video Answer


2 Answers

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.

like image 54
ken2k Avatar answered Oct 03 '22 05:10

ken2k


Adding virtual allows EF to generate a derived class that overrides the property and returns a set from the database.

like image 25
SLaks Avatar answered Oct 03 '22 03:10

SLaks