两个相反的modelBuilder关系设置之间有什么区别?

Mel*_*ssa 3 c# entity-framework-core

我使用EF Core代码优先,我有模型公司

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; }
}
Run Code Online (Sandbox Code Playgroud)

和模型联系.

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; }
}
Run Code Online (Sandbox Code Playgroud)

我尝试通过模型构建器在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);
Run Code Online (Sandbox Code Playgroud)

哪一个是正确的,有什么区别?

SO *_*ood 5

由于您正在使用Entity Framework Core,并且您正确地遵循Convention over Configuration:

// ClassName + Id
public Guid CompanyId { get; set; }
public Company Company { get; set; }
Run Code Online (Sandbox Code Playgroud)

那些ModelBuilder配置是:

  • 冗余 - 两个调用具有相同的效果,您可以使用对您来说最符合逻辑的调用.
  • 甚至更多的冗余-在EF的核心配置以下公约意味着你需要他们没有.

因此,当通过约定发现它们时,不需要通过Fluent API配置关系.

  • @Melianessa完全正确 (2认同)