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.
Adding virtual
allows EF to generate a derived class that overrides the property and returns a set from the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With