EF首先包含where子句db

时间:2017-11-21 18:09:00

标签: c# entity-framework

我在下面的链接中知道了另一个类似的问题,但是这些答案不起作用,因为我是db,并且实体框架加解决方案非常慢并且似乎只是获取每条记录并在之后过滤掉它。 EF: Include with where clause

司机和乘客是公共汽车上的导航财产。 preferredBrands是List<String>。基本上我想要的是所有的总线,其中typeid = 2,所有的驱动器,其优先品牌列在优先品牌列表中,以及所有乘客。以下查询抛出异常: The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path

var result =  db.busses.Where(h => h.bussesTypeId.Equals(2))
.Include(h => h.drivers.Where(p => preferredBrands.Contains(p.PrefferedBrand)))
.Include(h => h.passengers).ToList();

1 个答案:

答案 0 :(得分:-1)

&#39;包含&#39;只接受字符串参数而不是委托。您必须将Relational属性放在quote(string)中。这样做

var result =  db.busses
.Include("drivers.preferredBrands")
.Include("passengers")
.Where(h => h.bussesTypeId.Equals(2));

要访问驱动程序,请使用

result.drivers.where(p => preferredBrands.Contains(p.PrefferedBrand));

但是,如果您必须在include中使用委托,那么
1.参考Nuget的Z.EntityFramework 2.然后你可以使用&#39; IncludeFilter&#39;而是如下;

  using Z.EntityFramework.Plus;

  var result =  db.busses
  .IncludeFilter(h => h.drivers.Where(p => preferredBrands.Contains(p.PrefferedBrand)))
  .IncludeFilter(h => h.passengers)
  .Where(h => h.bussesTypeId.Equals(2)).ToList();

注意:您必须在where子句之前使用Include或IncludeFilter。它必须直接在EF实体上使用,而不仅仅在任何IEnumerable

上使用
相关问题