Question

I am new to Entity Framework and wondering why my foreign key property(s) has to be "virtual" even though data can be loaded without non virtual foreign key.

lets say i have two class. both have lines commented out with virtual keyword. data would still be loaded without virtual. Then why do we have to use virtual? does it has an impact once we add/update/delete records using Context.SaveChanges()?

public class Application
{
   public int ApplicationID{get;set;}
   public string Name{get;set;}

   //public virtual ICollection<ApplicationPages> Pages{get;set;}
   public ICollection<ApplicationPages> Pages{get;set;}
}

public class ApplicationPages
{
   public int ApplicationPageID{get;set;}
   public string Name{get;set;}

   public int ApplicationID{get;set;}
   [ForeignKey("ApplicationID")]
   public Application Application{get;set;}
   //public virtual Application Application{get;set;}
}
Was it helpful?

Solution

As I understand it, the virtual keyword is required to allow Entity Framework to make proxies of your classes, which assist in lazy loading situations.

I don't know the details of the proxy variant, but I'm guessing it brings back and stores child ids with the parent. Then, it you subsequently access child attributes (other than the id) it has an efficient way of fetching the child records.

I have had trouble with navigational properties on the parent, and left them out in favor of explicitly loading the child records when needed. However, my keys are two part (id and effective date) which may be the cause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top