【问题标题】:How do I get all child collection with generic repository pattern?如何使用通用存储库模式获取所有子集合?
【发布时间】:2018-06-17 16:46:28
【问题描述】:

我正在使用 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();
    }
}

当我像这样从应用程序var obj = _uow.HomeSection2s.GetAll() 调用GetAll 时,它不会填充详细信息。

【问题讨论】:

  • 所以使用Include
  • 考虑使用 .ToList() 返回 IQueryable 而不是 IEnumerable。通过使用 IQueryable,您的消费者可以决定如何处理实体,包括执行 .Include()、选择数据子集、进行计数、使用 .Any() 进行检查等。或者,您需要将参数传递给您的方法来指示您想要包含哪些扩展属性,然后在每个的 repo 方法中添加 .Include()。

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


【解决方案1】:

您的意思被称为“延迟加载”。这将要求您将这些属性设为虚拟,例如:

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

你也可以看看这个anwser

更多关于loading related data的文档

【讨论】:

  • 根据您的回答,在这部分return Query(eager).SingleOrDefault(i =&gt; i.EntityId == itemId);EntityId 指的是什么?
  • 它正在选择具有该 ID 的实体...在您的情况下,该示例将显示为 i =&gt; i.ID == someValue
  • 示例中的第一种方法是获取多个项目,第二种是如果您只想要一个。 (按身份证)。它假定所有模型都有一个 EntityId(它是主键)
猜你喜欢
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 2011-04-04
相关资源
最近更新 更多