Hassaan
Hassaan

Reputation: 3991

What is the purpose of virtual in Entity Framework?

I am a beginner to Entity Framework. I have got some terms which are creating problems. I am considering code-first schema

  1. 1-to-1 is resolved by by making a property of the child class in parent class and in child class we marks the id of parent class as foreign key.

    Like

    public class Parent{
       //code 
       public Child Child{get; set;}
    }
    
    public class Child{
       [ForeignKey("Parent")]
       public int ParentId{get; set;}
    }
    
  2. A 1-to-many relation we use

    public class Parent {
       //code 
       public IList<Child> Child { get; set; }
    }
    
    public class Child {
       [ForeignKey("Parent")]
       public int ParentId{get; set;}
    }
    

    Is this the correct approach?

  3. \*-\* is resolved by adding IList<class> in both classes.

But I was solving a problem where I have 2 classes Categories and Products.

In Product class a property is defined as

public class Products {
   public virtual Category Category { get; set; }
}

And in the Category class, products are called in this way

public class Categories {
   public virtual ICollection<Product> Products { get; set; }
}

I am confused what is the purpose of virtual Category in product?

Anyone answer please to resolve my confusion

Upvotes: 1

Views: 1979

Answers (1)

Dismissile
Dismissile

Reputation: 33071

As others have pointed out in the comments, EF uses the virtual keyword to enable lazy loading. The way it does this is by using what is known as a dynamic proxy.

If you are debugging you might notice that the type of your entity is not what you think it is:

Proxy types have names that look something like this: System.Data.Entity.DynamicProxies .Blog_5E43C6C196972BF0754973E48C9C941092D86818CD94005E9A759B70BF6E48E6

Entity Framework sees your Entity has the virtual keyword, and will create a dynamic proxy by inheriting from your class and overriding the properties that are marked virtual to enable lazy-loading for those properties.

As mentioned in the msdn I linked to, you will not get a dynamic proxy when you create an instance of your entity using the new keyword (and therefore will not get lazy loading):

var blog1 = new Blog(); // not a dynamic proxy
var blog2 = db.Blogs.Create(); // this is a dynamic proxy
var blog3 = db.Blogs.Find(1); // this is a dynamic proxy

Upvotes: 6

Related Questions