Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 920
Melianessa Avatar asked Jan 22 '19 12:01

Melianessa


People also ask

What are the different relationship patterns in Entity Framework?

Entity framework supports three types of relationships, same as database: 1) One-to-One 2) One-to-Many, and 3) Many-to-Many.

Which are the correct Fluent API methods for describing relationships?

When configuring a relationship with the fluent API, you start with the EntityTypeConfiguration instance and then use the HasRequired, HasOptional, or HasMany method to specify the type of relationship this entity participates in.

What is IEntityTypeConfiguration?

IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).


1 Answers

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.

like image 156
Camilo Terevinto Avatar answered Nov 15 '22 01:11

Camilo Terevinto