我先使用EF Core,然后使用代码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; }
}
和模型联系人。
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; }
}
然后,我尝试通过ModelBuilder在OnModelCreating方法中通过FluentAPI设置它们之间的关系。
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);
其中之一是正确的,有什么区别吗?
答案 0 :(得分:5)
由于您使用的是Entity Framework Core,因此您正确地遵循了Convention on Configuration:
// ClassName + Id
public Guid CompanyId { get; set; }
public Company Company { get; set; }
这些ModelBuilder配置为:
因此,当可以通过conventions发现关系时,就不需要通过Fluent API配置关系。