我在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; }
}
我需要通过BrandId
中Brand
的{{1}}表中找到ProductID
。
如何使用此通用包含来找到Product
?我应该将什么传递给该通用包含?
答案 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语句。