我有一个表,其中涉及国家,州和县,是孩子的县,是父母的国家,还是祖父母的国家。
我希望有一个雇员表,该表具有导航属性,该属性可以引用区域表中的子县,并且能够急于加载相关的子父母祖父母,我的意思是国家,州和县。
如何定义这种关系并渴望负荷?
我对模型的定义如下。
public enum RegionTypeEnum
{
Country = 0,
State = 1,
County = 2,
}
public class RegionType
{
public RegionTypeEnum Id { get; set; }
public string Name { get; set; }
}
public abstract class Region : Entity<int>
{
public int Id { get; set; }
public int? ParentId { get; set; }
public Region Parent { get; set; }
public RegionTypeEnum RegionTypeId { get; set; }
public RegionType RegionType { get; set; }
public string Name { get; set; }
}
public class Country : Region
{
}
public class State : Region
{
}
public class County : Region
{
}
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
// TODO define navigation to county and be able to eager load county, region and country
}
具有以下流利的API配置(为简洁起见,减少了代码)
// IEntityTypeConfiguration<Region>
builder.HasIndex(e => new { e.ParentId, e.Name }).IsUnique();
builder.Property(e => e.Name).IsRequired().HasMaxLength(80);
builder.Property(e => e.RegionTypeId).IsRequired().HasDefaultValue(RegionTypeEnum.Country);
builder.HasOne(e => e.Parent)
.WithMany()
.HasForeignKey(e => e.ParentId);
builder.HasOne(e => e.RegionType)
.WithMany()
.HasForeignKey(e => e.RegionTypeId)
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
builder.HasDiscriminator(e => e.RegionTypeId)
.HasValue<Country>(RegionTypeEnum.Country)
.HasValue<State>(RegionTypeEnum.State)
.HasValue<County>(RegionTypeEnum.County);
// IEntityTypeConfiguration<RegionType>
builder.Property(e => e.Id).ValueGeneratedNever();
builder.Property(e => e.Name).IsRequired().HasMaxLength(10);