I have the following class:
public class Delivery
{
// Primary key, and one-to-many relation with Customer
public int DeliveryID { get; set; }
public virtual int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
// Properties
string Description { get; set; }
}
Can someone explain why they Customer information is coded with virtual. What does it mean?
Judging by the comments, you are learning Entity Framework?
virtual here would mean you are trying to use lazy loading - when related items like Customer can be loaded by EF automatically
http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx
For example, when using the Princess entity class defined below, the related unicorns will be loaded the first time the Unicorns navigation property is accessed:
public class Princess
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Unicorn> Unicorns { get; set; }
}
Can someone explain why they Customer information is coded with virtual. What does it mean?
The virtual keyword means that a super class derived from this base class (i.e. Delivery) can override that method.
If the method was not marked as virtual then it would not be possible to override that method.
Guess you are using EF.
What happens when you make a NavigationProperty
virtual is that EF dynamically creates a derived class.
That class implements functionality that allows for lazy loading and other tasks like maintaining relations that EF performs for you.
Just to get the idea your sample class dynamically becomes something like this:
public class DynamicEFDelivery : Delivery
{
public override Customer Customer
{
get
{
return // go to the DB and actually get the customer
}
set
{
// attach the given customer to the current entity within the current context
// afterwards set the Property value
}
}
}
You can easily see this while debugging, the actual instance types of your EF classes have very weird names, since they are generated on the fly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With