【问题标题】:Add Where clause to IQueryable将 Where 子句添加到 IQueryable
【发布时间】:2018-09-11 08:59:26
【问题描述】:

我有一个问题:

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 子句?

【问题讨论】:

  • 你需要一个IQueryable&lt;Order&gt;

标签: c# entity-framework linq


【解决方案1】:

您可以在 IQueryable 中添加实体类型

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

然后更新你调用这个方法的地方

IQueryable<Order> query = GetIncludes(Context);

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 2015-04-21
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多