简体   繁体   English

SQL Top 1与System.Linq firstordefault

[英]sql Top 1 vs System.Linq firstordefault

I am rewriting an SProc in c#. 我正在用C#重写SProc。 the problem is that in SProc there is a query like this: 问题是在SProc中有这样的查询:

select top 1 *
from ClientDebt
where ClinetID = 11234
order by Balance desc

For example :I have a client with 3 debts, all of them have same balance. 例如:我有一个有3笔债务的客户,他们所有人都有相同的余额。 the debt ids are : 1,2,3 债务编号为:1,2,3

c# equivalent of that query is : 该查询的C#等效项是:

debts.OrderByDescending(d => d.Balance)
     .FirstOrDefault()

debts represent clients 3 debts 债务代表客户3笔债务

the interesting part is that sql return debt with Id 2 but c# code returns Id 1. The Id 1 make sense for me But in order to keep code functionality the same I need to change the c# code to return middle one. 有趣的部分是sql返回带有Id 2的债务,但是c#代码返回ID1。Id1对我来说很有意义,但是为了保持代码功能相同,我需要更改c#代码以返回中间的代码。

I do not sure what is the logic behind sql top 1 where several rows match the query. 我不确定sql top 1后面有几行与查询匹配的逻辑是什么。

The query will select one debt and update the database. 该查询将选择一个债务并更新数据库。 I would like the linq to return the same result with sql 我希望linq用sql返回相同的结果

Thanks 谢谢

debts.OrderByDescending(d => d.Balance).ThenByDescending(d => d.Id)
     .FirstOrDefault()

You can start SQL Profiler, execute stored procedure, review result, and then catch query which application send through linq, and again review result. 您可以启动SQL事件探查器,执行存储过程,查看结果,然后捕获查询通过linq发送的应用程序,然后再次查看结果。

Also, you can easily view execution plan of you procedure, and try it to optimize, but with linq query, you cannot easily do this. 另外,您可以轻松查看过程的执行计划,并尝试对其进行优化,但是使用linq查询,您将无法轻松地做到这一点。

AFAIK, IN SQL if you select rows without ORDER BY, it orders the resultset based on the primary key. AFAIK,在SQL中,如果选择不带ORDER BY的行,它将基于主键对结果集进行排序。 With Order BY CLAUSE [field], implicitly next order is [primarykey]. 使用Order BY CLAUSE [field],隐式下一个订单是[primarykey]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM