问题
I had a table that relates Country, State and County, being county the child, state the parent and country the grandparent.
I want to have a employee table with a navigation property that could reference to a child county in region table and be able to eager load related child parent grandparent, I mean Country, State and County.
How can I define such relation and eager load?.
I had define the models as follows..
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
}
with the following fluent API configuration (code reduced for brevity)
// 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);
来源:https://stackoverflow.com/questions/54999120/ef-core-navigation-property-for-eager-load-child-parent-grandparent