I am facing a slight problem and hope you could help, basically I would like to get children of children in Generic repository pattern as I have relationship table with multi-multi relationship
My Repository method looks like that:
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));
}
My model:
Product:
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; }
}
Ingredient:
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; }
}
Relationship:
public class ProductIngredient : BaseEntity<long>
{
[ForeignKey("Id")]
public long? ProductId { get; set; }
[ForeignKey("Id")]
public long? IngredientId { get; set; }
}
What I'd like to achieve is to populate my ProductDto with ProductData and List of ingredients, my current ProductDto looks like:
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; }
}
I've found that I can use "ThenInclude" to include children of children, just don't know how to implement this to generic repository.
What I can do so far is just take a children then which for example I'm doing like that:
var results = await _productsRepository.FindAsync(p => p.Id == id, p => p.ProductIngredient);
Any help much appreciated. Thanks!