在ASP.NET Core中使用通用包含函数

时间:2019-02-03 15:51:35

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

我在ASP.NET Core中具有此泛型包含:

 public IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
 {
     IQueryable<T> query = _uow.Set<T>();

     return includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
 }

我有两个表:

public class Brand
{
    public int BrandId { get; set; }
    public string BFaName { get; set; }
    public string BEnName { get; set; }
    public int CatId { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
    public virtual ICollection<ProductBrand> ProductBrands { get; set; }
}

public class ProductBrand
{
    public int Id { get; set; }
    public virtual Brand Brand { get; set; }
    public virtual Product Product { get; set; }
}

我需要通过BrandIdBrand的{​​{1}}表中找到ProductID

如何使用此通用包含来找到Product?我应该将什么传递给该通用包含?

1 个答案:

答案 0 :(得分:0)

我认为include函数可以按预期工作。然后

int brandId = 12;

var product = AllIncluding(a => a.Product).Single(a => a.Id == brandId);

// your result here
var brand = product.Brand;

或“单身”

var brand = AllIncluding(a => a.Product)
     .Single(a => a.Id == 12)
     .Select(a => a.Brand);
  

请注意,Single不是null安全的!

如果您需要更多物品:

var brand = AllIncluding(a => a.Product, a => a.Brand, ...)
...

由于使用关键字params,因此可以一次传递多个include语句。