7

我正在使用 Entity Framework 4 构建一个 ASP.Net MVC 3 应用程序。当执行下面的两条代码时,两个变量(query1 和 query2)的返回类型为

System.Data.Objects.ObjectQuery<Asset.Model.Equipment>

Query1 使用 ObjectContext 的直接实例,而 Query2 使用存储库模式,即它调用 EquipmentService 中的 GetEquipment,而后者又调用 Equipment Repository 中相同命名的方法。Service 和 Repository 中的方法都返回

IQueryable<Equipment>

如何,这是我的问题,为什么 query2 仅在我包含时才有效

using System.Linq.Dynamic;

在我的控制器顶部

using (AssetEntities context = new AssetEntities())
        {
            var query1 = context.Equipments
            .OrderBy("it." + sidx + " " + sord)
            .Skip(pageIndex * pageSize)
            .Take(pageSize);
        }


        var query2 = equipService.GetEquipment()
            .OrderBy(sidx + " " + sord)
            .Skip(pageIndex * pageSize)
            .Take(pageSize);

如果我从控制器中省略 System.Linq.Dynamic,则会在 Query2 中收到错误

.OrderBy(sidx + " " + sord)

哪个州

The type arguments for method 'System.Linq.Queryable.OrderBy<TSource,TKey>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,TKey>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly

有谁知道为什么 query1 可以在不使用 System.Linq.Dynamic 的情况下工作,但是 query2 需要它来执行?

谢谢大家。

4

2 回答 2

6

在第一个查询context.Equipments中有 type ObjectQuery<Equipment>。具有需要的ObjectQuery<T>方法OrderBy(string).OrderBy("it." + sidx + " " + sord)。所以第一个查询工作。

在第二个查询中,您使用equipService.GetEquipment()type IQueryable<Equipment>。有唯一的IQueryable<T>扩展方法OrderByExpression<Func<T, TKey>>作为参数而不是string. 所以要和你一起使用OrderByIQueryable<Equipment>你必须写一些类似的东西

equipService.GetEquipment().OrderBy(e => e.equipmentID)

但这不是您可以使用的。您需要另一种扩展方法,它可以为您提供 form 的 LINQ 动态查询库System.Linq.Dynamic

在许多情况下,LINQ to Entities 有很多限制,但在您的情况下,它与 LINQ to SQL 相比具有更多优势。所以我建议你在你的情况下继续使用 LINQ to Entities。我相信,由于直接在您使用的实体框架中对所有功能的原生支持,您将获得更好的性能。

因为 LINQ to Entities 或ObjectQuery<Equipment>支持Where(string)方法(确切地说是ObjectQuery.Where(string predicate, params ObjectParameter[] parameters)方法),您可以相对容易地在 jqGrid 中实现过滤/搜索。的用法.Where可以

.Where("it.equipmentID < 100")

或者

.Where("it.equipmentID < @maxId", new ObjectParameter ("maxId", 100))

例如(在ObjectParameter未输入错误中使用“maxId”而不是“@maxId”)。

更新:在答案的“更新”部分,您可以找到示例,该示例显示了如何根据我上面描述的想法在 jqGrid 中实现过滤/搜索。

于 2011-03-01T18:04:54.580 回答
4

“它”是默认的ObjectQuery.Name属性值。事实上,当您使用第一个查询时,您执行了一个隐式的 Entity SQL Order By 子句,而在第二个查询中您使用的是 LINQ to Entities,它需要 System.Linq.Dynamic 命名空间才能正常工作。

于 2011-02-28T12:40:04.433 回答