Emran Hussain
Emran Hussain

Reputation: 12059

Is there any benefit for marking the Simple Entity Property as virtual for Entity Framework CodeFirst 4.1

I know that I can use virtual keyword to tell the entity framework that the child table should be loaded LAZY way. as,

public class Person
{
    public virtual string Name { get; set; }
    public virtual int Age { get; set; }
    public virtual History PastHistory { get; set; }
    public virtual ICollection<Blog> Blogs { get;set; }   
}

public class Blog
{
   ..... blah.. blah.... blah
}

public class History
{
   .... blah blah blah
}

Now, my question,

  1. As History is not a collection but 1:1 mapping for another entity, should I mark History as Virtual if I want to load History Lazy way ?

  2. Is there any benefit for marking the simple properties (i.e. Name: string, Age : int) as virtual ? At this moment, I marked all my simple properties as virtual for no obvious reason. If anyone confirms me that marking simple properties as virtual has no effect at all in EF Code First, I will remove the marks to look my POCO clearer.

Thanks.

Upvotes: 1

Views: 264

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

  1. If History is still related entity (record from another table) you must also mark it virtual to enable lazy loading. What is even more important if you want to use lazy loading for Blogs all other navigation properties in entity must be virtual as well.
  2. Marking all simple properties virtual will allow EF to use dynamic change tracking.

Both lazy loading and change tracking is performed by dynamic proxy - a type created at runtime and derived from your entity type. Virtual keyword is necessary to allow this derived type to override (wrap) your property code into new code performing either lazy loading of navigation property or informing EF context about changes in simple property.

Upvotes: 4

Related Questions