OrderBy的正确行为
我遇到了令我困惑的事情,我希望看到你对此事的看法。 事实certificate,linq对sql和entity framework的威胁是连续的顺序。
以下代码仅用于示例,我并未声称它有任何意义:
Linq to sql:
DataClasses1DataContext db = new DataClasses1DataContext(); var result = (from c in db.Products orderby c.ProductName orderby c.UnitPrice orderby c.UnitsOnOrder select c).ToList();
它在服务器端产生的是什么:
SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued] FROM [dbo].[Products] AS [t0] ORDER BY [t0].[UnitsOnOrder], [t0].[UnitPrice], [t0].[ProductName]
与Entity Framework进行的相同测试会生成以下内容:
SELECT [Extent1].[ProductID] AS [ProductID], [Extent1].[ProductName] AS [ProductName], [Extent1].[SupplierID] AS [SupplierID], [Extent1].[CategoryID] AS [CategoryID], [Extent1].[QuantityPerUnit] AS [QuantityPerUnit], [Extent1].[UnitPrice] AS [UnitPrice], [Extent1].[UnitsInStock] AS [UnitsInStock], [Extent1].[UnitsOnOrder] AS [UnitsOnOrder], [Extent1].[ReorderLevel] AS [ReorderLevel], [Extent1].[Discontinued] AS [Discontinued] FROM [dbo].[Products] AS [Extent1] ORDER BY [Extent1].[UnitsOnOrder] ASC
正如您所看到的,Linq To Sql添加了所有请求的顺序,其中最后一个具有最高优先级(在我看来是正确的)。 另一方面,entity framework仅尊重最后一个订单,而忽略所有其他订单。
现在我知道有一个by by by子句可以使用,但我只是想知道哪种行为更正确。 另外,据我记得,asp中使用的查询扩展器正在使用单独的顺序,如果应用于从不同数据源生成的查询,将无法正常工作(根据上面的示例,将省略其中一个顺序)
我认为EF是正确的。 我不知道为什么L2S会做你所描述的 – 在我看来,如果你添加一个OrderBy
子句而不是使用ThenBy
,它应该覆盖任何现有的OrderBy
。
当您使用Linq-To-Objects时,您应该看到OrderBy
替换以前的任何一个,所以让数据驱动的LINQ行为相同对我来说更有意义。
如果行为改变了你描述的方式,那么微软似乎同意,因为EF旨在取代L2S。
我所学到的是订单是这样写的:
DataClasses1DataContext db = new DataClasses1DataContext(); var result = (from c in db.Products orderby c.UnitsOnOrder, c.UnitPrice, c.ProductName select c).ToList();
就像那样,你可以看到每个人的订单都清楚。