Reputation: 5449
Hi I am just learning to work with Entity Framework Code First and I can not seem to understand something.I have created three models based on a tutorial:
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments{ get; set; }
}
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public decimal? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
public class Student
{
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
My problem is that I do not understand what the properties with virtual do.If I check the database there is no column crate for each of the properties , only for the others.
So what happens when you create a property with the virtual keyword?
Upvotes: 29
Views: 29825
Reputation: 48965
It is used to manage lazy loading and change tracking.
EF will generate proxy types on runtime, which are dynamically generated types that inherit from your POCO classes and add all the EF stuff to manage lazy loading / change tracking in the overridden virtual properties.
So virtual
is not a "magic keyword" here, virtual
is here so your POCOs can be inherited with additional EF-related code at runtime.
Upvotes: 41
Reputation: 5801
When you create a property or method marked with the virtual keyword, you will be allowed to override it in a derived class, thus offering your method a more specialized behaviour depending on the objects you create.
In the case of Entity Framework its also a convention that points out that lazy loading behaviour is used. A question regarding this matter exists here: Entity Framework 4.1 Virtual Properties
Upvotes: 3