Linq To SQL:按任意属性(列)名称对查询进行排序 [英] Linq To SQL: Sort Query by Arbitrary Property(Column) Name
问题描述
我有一个更大/更复杂的问题,但为简单起见,让我们考虑以下问题:
I have a larger/more complex problem, but for simplicity sake, let us consider the following:
让我们说我在 SQL数据库中有一个名为 Product 的表,该表有两列 ID (int,主要键)和名称((varchar/字符串)).我还有一个简单的 LINQ DataContext .
Let us say that I have table in the SQL DataBase called Product, having two columns, ID (int, primary key) and Name (varchar/string). I also have a simple LINQ DataContext.
我构造了一个查询并将其交给我的"函数.让我们说这就像:(尽管可能会更复杂)
I have a query constructed and handed to "my" function. Let us say it is something like: (though it may be a bit more complex)
IQueryable<Product> query = from p in db.Products select p;
一旦我的方法获得此查询并作为参数传递,它就必须更改排序顺序,例如
Once my method gets this query, passed in as a parameter, it has to change the sort order e.g.
IQueryable<Product> sortedQuery = query.OrderBy(x => x.Name);
我想使它更通用,即指定要排序的字段.通常,我可以执行一个包含字符串的switch
语句.但是我想知道是否有一种直接传递参数的方法.我打算将此扩展到其他数据库表,因此这些switch
语句将变得乏味.
I would like to make this more generic i.e. to specify the field to sort on. Normally, I can do a switch
statement that takes a string. However I would like to know if there is a way to pass the parameter directly. I intend to extend this to other Database tables, so these switch
statements would get tedious.
我正在尝试类似的事情:
I was trying something like:
IQueryable<Product> sortedQuery = query.OrderBy(x => (typeof(Product)).GetProperty("Name"));
但这不起作用.我还想确保维护LINQ to SQL,即要在SQL Server上进行的排序.因此,如果我进行调试,则应该从此LINQ查询中获取一个SQL查询.
But this does not work. I also want to ensure that the LINQ to SQL is maintained i.e. the sort to be done on the SQL Server. Hence if I debug, I should get a SQL query from this LINQ query.
预先感谢您的帮助.
推荐答案
您可以为此目的使用Dynamic Linq
.
Then you can make calls like this:
var query = DBContext.Users.Where( "Age > 3" ).OrderBy( "Name asc" );
这篇关于Linq To SQL:按任意属性(列)名称对查询进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!