OrderBy("it." + sort)-在LINQ to Entity框架中进行硬编码? [英] OrderBy("it." + sort) -- Hard coding in LINQ to Entity framework?

查看:60
本文介绍了OrderBy("it." + sort)-在LINQ to Entity框架中进行硬编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在应用程序中使用动态LINQ to Entity来在运行时指定OrderBy属性.但是,按照大多数文档中的说明使用代码时:

I have been trying to use dynamic LINQ to Entity in my application for specifying the OrderBy attribute at runtime. However when using the code as described in the majority of documentation:

var query = context.Customer.OrderBy("Name");

我收到以下异常:

System.Data.EntitySqlException:在当前范围或上下文中无法解析名称".确保所有引用的变量都在作用域内,已加载所需的架构,并且正确引用了名称空间.

经过大量搜索,我找到了这个MSDN页面:

After much searching I found this MSDN page:

http://msdn.microsoft.com/en-us/library/bb358828.aspx

其中包含以下代码示例:

Which included the following code example:

ObjectQuery<Product> productQuery2 = productQuery1.OrderBy("it.ProductID");

这提示我将代码更改为以下内容:

This prompted me to change my code to the following:

var query = context.Customer.OrderBy("it.Name");

此后,代码可以正常工作.任何人都可以确认这确实是使OrderBy与LINQ一起使用到Entity的正确方法吗?我不敢相信该框架会以这种方式实现,也许我忽略了一些东西?

After this the code works perfectly. Would anyone be able to confirm that this is indeed the correct way to get OrderBy working with LINQ to Entity? I can’t believe that the framework would have been implemented in this way, perhaps I have overlooked something?

谢谢,马特

推荐答案

it.Name语法是ESQL,确实特定于EF.有时有充分的理由使用它(例如,排序规则说明符),但这不是我通常要做的.

The it.Name syntax is ESQL and is indeed specific to the EF. There are good reasons to use this sometimes (e.g., collation specifiers), but it's not what I normally do.

通常,我使用标准的LINQ表达式:

Usually I use standard LINQ expressions:

var query = context.Customer.OrderBy(p => p.Name);

如果从Code Gallery下载System.Linq.Dynamic,也可以使用System.Linq.Dynamic,然后使用原始查询:

You can also use System.Linq.Dynamic, if you download it from Code Gallery, and then your original query:

var query = context.Customer.OrderBy("Name");

...将起作用.

这篇关于OrderBy("it." + sort)-在LINQ to Entity框架中进行硬编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆