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)
哪一个是正确的,有什么区别?
由于您正在使用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配置是:
因此,当通过约定发现它们时,不需要通过Fluent API配置关系.