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?
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.