У одной компании может быть много адресов, однако у каждой компании есть основной адрес.
Я ищу, как найти лучший способ создания такого рода отношений в EF Core.
Вот то, что я придумал. Есть ли способ лучше? Я полностью ухожу?
Модель
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
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);
}
}