[英]One to Many with One Main in Code-First Entity Framework Core
One company can have many addresses, however each company has a main address. 一个公司可以有多个地址,但是每个公司都有一个主要地址。
I am looking to find the best way to create this kind of relation in EF Core. 我正在寻找找到在EF Core中创建这种关系的最佳方法。
Below is what I came up with. 下面是我想出的。 Is there a better way?
有没有更好的办法? Am I way off entirely?
我会完全离开吗?
Models 楷模
public class Company
{
public int Id { get; set; }
public int MainAddressId { get; set; }
public Address MainAddress { get; set; }
public ICollection<CompanyAddress> CompanyAddresses { get; set; }
// other company info
}
public class Address
{
public int Id { get; set; }
public int CompanyAddressId { get; set; }
public CompanyAddress CompanyAddress { get; set; }
// other address info
}
public class CompanyAddress
{
public int CompanyId { get; set; }
public Company Company { get; set; }
public int AddressId { get; set; }
public Address Address { get; set; }
public bool IsMain { get; set; }
}
DataContext.cs DataContext.cs
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<Company> Companies { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<CompanyAddress> CompanyAddresses { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<CompanyAddress>()
.HasKey(ca => new {ca.CompanyId, ca.AddressId});
builder.Entity<CompanyAddress>()
.HasOne(ca => ca.Company)
.WithMany(ca => ca.CompanyAddresses)
.HasForeignKey(ca => ca.CompanyId)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<CompanyAddress>()
.HasOne(ca => ca.Address)
.WithOne(ca => ca.CompanyAddresses)
.HasForeignKey(ca => ca.AddressId)
.OnDelete(DeleteBehavior.Cascade);
}
}
In my opinion, dead on. 我认为,继续下去。 There are always other ways.
总有其他方法。 But this is straight-forward and easily understood.
但这很简单,很容易理解。 MainAddress and MainAddressId are redundant.
MainAddress和MainAddressId是冗余的。 You don't have lazy loading (virtual) so you can easily determine the main address by
您没有延迟加载(虚拟),因此可以通过以下方式轻松确定主地址
dbContext.Companies.FirstOrDefault(p => p.Id = <myCompanyId>);
dbContext.CompanyAddresses.FirstOrDefault(p => p.CompanyId == <myCompanyId> && p.IsMain);
If you go with lazy loading later, just add .Include("Address") to the second query. 如果以后要进行延迟加载,只需将.Include(“ Address”)添加到第二个查询中。 And yes, you can combine the two.
是的,您可以将两者结合起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.