将Where子句添加到IQueryable

时间:2018-09-11 08:59:27

标签: c# entity-framework linq

我有一个查询:

public IQueryable GetOrder(int id)
{
  using (Context = new MyEntities())
  {
    IQueryable query = Context.Orders
     .Include("Customers")
     .Include("Products")
     .Include("OrderLines")
     .Where(o => o.OrderID == id);
    return query;
  }
}

现在,我想提取基本查询(没有.Where子句的所有内容),以便可以在其他方法中重用它。我尝试过:

private IQueryable GetIncludes(MyEntities context)
{
  return context.Orders
   .Include("Customers")
   .Include("Products")
   .Include("OrderLines");
}

public IQueryable GetOldOrders()
{
  using (Context = new MyEntities())
  {
    DateTime ninetyDaysAgo = new DateTime(DateTime.Now.AddDays(-90));

    IQueryable query = GetIncludes(Context);
    query = query.Where(o => o.OrderDate < ninetyDaysAgo);
    return query;
  }
}

但是编译器告诉我Cannot convert lambda expression to type 'string' because it is not a delegate type

我查看了Cannot convert lambda expression to type 'string' because it is not a delegate type,并可以报告我正在使用System.Linq(和System.Linq.Dynamic)和System.Data.EntitySystem.Data.Entity在VS中呈灰色。

如何创建一个IQueryable,可以在创建后添加一个.Where子句?

1 个答案:

答案 0 :(得分:2)

您可以将实体类型添加到IQueryable

private IQueryable<Order> GetIncludes(MyEntities context)
{
  return context.Orders
   .Include("Customers")
   .Include("Products")
   .Include("OrderLines");
}

然后更新您调用此方法的位置

IQueryable<Order> query = GetIncludes(Context);