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?
Entity framework supports three types of relationships, same as database: 1) One-to-One 2) One-to-Many, and 3) Many-to-Many.
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.
IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).
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:
Thus, there's no need to configure relations via Fluent API when they can be discovered via conventions.
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