在C#Generic Repository EF中包含孩子的孩子

时间:2017-08-19 15:04:42

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

我正面临一个小问题,并希望你能帮忙,基本上我想通过Generic存储库模式让孩子的孩子,因为我有多关系的关系表

我的存储库方法如下所示:

public IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includes)
    {
      var query = _entities.Where(predicate).AsQueryable();
      if (includes != null)
      {
        query = includes.Aggregate(query, (current, include) => current.Include(include));
      }
      return query;
    }

public async Task<IQueryable<TEntity>> FindAsync(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includes)
    {
      return await Task.Run(() => Find(predicate, includes));
    }

我的模特:

产品:

public class Product : BaseEntity<long>
  {
    [MaxLength(100)]
    public string Name { get; set; }
    [MaxLength(100)]
    public string Barcode { get; set; }
    public int ShelfLife { get; set; }
    public int Weight { get; set; }
    public bool HasAllergens { get; set; }
    [ForeignKey("Id")]
    public int CustomerId { get; set; }
    public virtual ICollection<ProductIngredient> ProductIngredient { get; set; }
  }

成分:

public class Ingredient : BaseEntity<long>
  {
    [MaxLength(100)]
    public string Name { get; set; }
    [ForeignKey("Id")]
    public int CustomerId { get; set; }
    public virtual ICollection<ProductIngredient> ProductIngredient { get; set; }
  }

关系:

public class ProductIngredient : BaseEntity<long>
  {
    [ForeignKey("Id")]
    public long? ProductId { get; set; }
    [ForeignKey("Id")]
    public long? IngredientId { get; set; }
  }

我想要实现的是使用ProductData和成分列表填充我的ProductDto,我当前的ProductDto看起来像:

public class ProductDto
    {
      public long Id { get; set; }
      public DateTime CretedOn { get; set; }
      public DateTime UpdatedOn { get; set; }
      public string Name { get; set; }
      public string Barcode { get; set; }
      public int ShelfLife { get; set; }
      public int Weight { get; set; }
      public bool HasAllergens { get; set; }
      public int CustomerId { get; set; }
      public IList<IngredientDto> Ingredients { get; set; }
  }

我发现我可以使用“ThenInclude”来包含孩子的孩子,只是不知道如何将其实现到通用存储库。

到目前为止,我能做的只是带一个孩子,例如我正在这样做:

var results = await _productsRepository.FindAsync(p => p.Id == id, p => p.ProductIngredient);

任何帮助非常感谢。 谢谢!

0 个答案:

没有答案