What's the difference between two opposite modelBuilder relationship settings?

c# entity-framework-core

Question

I use EF Core with code-first and I have model Company

public class Company
{
    public Guid Id { get; set; }        
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime FoundationDate { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Logo { get; set; }
    public ICollection<Contact> Contacts { get; set; }
}

and model Contact.

public class Contact
{
    public Guid Id { get; set; }            
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public Guid CompanyId { get; set; }
    public Company Company { get; set; }
    public ICollection<Resource> Resources { get; set; }
}

And I try to set relationships between them via FluentAPI in OnModelCreating method through modelBuilder.

modelBuilder.Entity<Company>()
            .HasMany<Contact>(s => s.Contacts)
            .WithOne(g => g.Company)
            .HasForeignKey(s => s.CompanyId);

modelBuilder.Entity<Contact>()
            .HasOne<Company>(s => s.Company)
            .WithMany(g => g.Contacts)
            .HasForeignKey(s => s.CompanyId);

Which one of them is correct and is there any difference?

1
3
1/22/2019 12:20:38 PM

Accepted Answer

Since you are using Entity Framework Core, and you follow Convention over Configuration correctly:

// ClassName + Id
public Guid CompanyId { get; set; }
public Company Company { get; set; }

Those ModelBuilder configurations are:

  • Redundant - both calls have the same effect and you can use the one that seems most logical to you.
  • Even more redundant - following Convention over Configuration in EF Core means you need none of them.

Thus, there's no need to configure relations via Fluent API when they can be discovered via conventions.

5
1/22/2019 12:37:58 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow