In Code First and Entity Framework tutorials I have found different examples showing the use of the property virtual
in different models.
Example:
public class Student {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
Another example:
public class Album {
public virtual int AlbumId { get; set; }
public virtual int GenreId { get; set; }
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
So my question is the following, what is the use of the property virtual
and when to use it?
virtual
allows a property and method to be overridden by a class that inherits from it.The cases in which I have used it have been more when I need to modify the default behavior of the class, for example, when obtaining the name, I convert it to uppercase since the main class does not.
When using virtual you are using LazyLoading and the relationship entities will be loaded, meanwhile if you do not use virtual you are using Eager Loading which in order to access the navigation properties you must use the Inclide() method
Eager loading example:
You would have to use Include() when you want some navigation property.