EF Core navigation property for eager load child parent grandparent

好久不见. 提交于 2019-12-25 01:45:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!