如何使用通用存储库模式获取所有子集合?

时间:2018-06-17 08:19:04

标签: c# entity-framework asp.net-core asp.net-core-mvc

我正在使用EF Core 2.1,我在我的域中拥有这些类。

public class HomeSection2
{
    public HomeSection2()
    {
        HomeSection2Detail = new List<HomeSection2Detail>();
    }

    public Guid ID { get; set; }
    public string Title { get; set; }
    public string Header { get; set; }

    public List<HomeSection2Detail> HomeSection2Detail { get; set; }
}

public class HomeSection2Detail
{
    public Guid ID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Link { get; set; }
    public int? Sequence { get; set; }

    public HomeSection2 HomeSection2 { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.RemovePluralizingTableNameConvention();

    //HomeSection2
    modelBuilder.Entity<HomeSection2>().HasKey(s => s.ID);
    modelBuilder.Entity<HomeSection2>().Property(s => s.ID).ValueGeneratedOnAdd();
    modelBuilder.Entity<HomeSection2>().Property(s => s.Title).IsRequired();
    modelBuilder.Entity<HomeSection2>().Property(s => s.Header).IsRequired();

    //HomeSection2Detail
    modelBuilder.Entity<HomeSection2Detail>()
        .HasOne(p => p.HomeSection2)
        .WithMany(b => b.HomeSection2Detail);
    modelBuilder.Entity<HomeSection2Detail>().HasKey(s => s.ID);
    modelBuilder.Entity<HomeSection2Detail>().Property(s => s.ID).ValueGeneratedOnAdd();
    modelBuilder.Entity<HomeSection2Detail>().Property(s => s.Title).IsRequired();
    modelBuilder.Entity<HomeSection2Detail>().Property(s => s.Sequence).IsRequired();
}

我有一个通用的回购

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    protected readonly DbContext Context;

    public Repository(DbContext context)
    {
        Context = context;
    }

    public IEnumerable<TEntity> GetAll()
    {
        return Context.Set<TEntity>().ToList();
    }
}

当我从这样的应用GetAll拨打var obj = _uow.HomeSection2s.GetAll()时,它就不会填写详细信息。

1 个答案:

答案 0 :(得分:-1)

你的意思被称为'延迟加载'。它需要您将这些属性设置为虚拟,例如:

public virtual List<HomeSection2Detail> HomeSection2Detail { get; set; }

您还可以查看此anwser

有关loading related data

的更多文档