Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First?

Does the virtual keyword has an effect when used on the properties in EF Code First?. Can someone describe all of its ramifications in different situations?

For instance, I know it can control lazy loading -- if you use the virtual keyword on an ICollection/one-to-many relationship property, it will be lazy-loaded by default, whereas if you leave the virtual keyword out, it will be eager-loaded.

What other effects can virtual keyword have in EF with POCO entities?. Should I make it default to use virtual on all my properties, or default to not using it?

like image 384
Scott Stafford Avatar asked Apr 08 '11 16:04

Scott Stafford


People also ask

What is the use of virtual keyword in Entity Framework?

You should use virtual keyword, when you want to load data with lazy loading. lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time it is accessed. Lazy loading of the Posts collection can be turned off by making the Posts property non-virtual.

Why navigation properties are virtual?

If you define your navigation property virtual , Entity Framework will at runtime create a new class (dynamic proxy) derived from your class and uses it instead of your original class. This new dynamically created class contains logic to load the navigation property when accessed for the first time.


1 Answers

So far, I know of these effects.

  • Lazy Loading: Any virtual ICollections will be lazy-loaded unless you specifically mark them otherwise.
  • More efficient change tracking. If you meet all the following requirements then your change tracking can use a more efficient method by hooking your virtual properties. From the link:

    To get change tracking proxies, the basic rule is that your class must be public, non-abstract or non-sealed. Your class must also implement public virtual getters/setters for all properties that are persisted. Finally, you must declare collection based relationship navigation properties as ICollection<T> only. They cannot be a concrete implementation or another interface that derives from ICollection<T> (a difference from the Deferred Loading proxy)

Another useful link describing this is MSDN's Requirements for Creating POCO Proxies.

like image 187
Scott Stafford Avatar answered Sep 25 '22 05:09

Scott Stafford