Suppose I have 2 related entities with a one to many relationship: Company and Job.
In the Company Class:
public class Company {
public int companyId {get; set;}
...other properties
public **virtual** ICollection<Job> jobs {get; set;}
}
In the Job class
public class Job{
public int jobId {get; set;}
...other properties
public int companyId {get; set;}
public Company company {get; set;}
}
-
Why do we sometimes put the virtual keywords when there’s a collection property?
-
Why do we add the companyId alongside the Company property instead of just having the Company property that does all the work?
-
Why do we need to configure the onModelCreating method to apply the foreign keys ? isn’t it done automatically?
2
Answers
OnModelCreating
unless you want to override the defaults.1.virtual was never required in EF. It was needed only if you want lazy loading support and more efficient change tracking.
If you turn on Lazy Loading, all navigation properties (e.g. Non Primitives), are required to be virtual.
2.When you want to query for get customerid(find customerid==5) , you don’t need to add an additional query to the customer table.(d.customer.id==5)
You can directly use the customer Id and You can easily change the attribute of the ForeignKey, such as not being null
3.Configuration can be applied in two ways, using the Fluent API, and through DataAnnotation attributes.Attributes are a kind of tag that you can place on a class or property to specify metadata about that class or property.
you use DataAnnotation and attributes in class or field that the EF itself creates the required class exmple(ForeignKey)
data-annotation-attributes
Example
EF Core’s Fluent API provides methods for configuring various aspects of your model that is more powerful and is flexabile
fluent-api
In the second method, you need this method OnModelCreating
Example:
relationships