skip to Main Content

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;}

}
  1. Why do we sometimes put the virtual keywords when there’s a collection property?

  2. Why do we add the companyId alongside the Company property instead of just having the Company property that does all the work?

  3. Why do we need to configure the onModelCreating method to apply the foreign keys ? isn’t it done automatically?

2

Answers


    1. Virtual properties are used when you want to use lazy loading.
    2. You don’t need an id property, unless you need it yourself for something, the column will automatically (and silently) added by EF to the migrations.
    3. EF configuration is by convention, you do not need to add an OnModelCreating unless you want to override the defaults.
    Login or Signup to reply.
  1. 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

    public int? companyId {get; set;}
    

    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

    public ICollection<Post> Posts { get; } = new List<Post>(); 
    

    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:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasMany(e => e.Posts)
            .WithOne(e => e.Blog)
            .HasForeignKey("BlogId")
            .IsRequired();
    }
      
    

    relationships

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search