简体   繁体   中英

sql Top 1 vs System.Linq firstordefault

I am rewriting an SProc in c#. the problem is that in SProc there is a query like this:

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. the debt ids are : 1,2,3

c# equivalent of that query is :

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

debts represent clients 3 debts

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.

I do not sure what is the logic behind sql top 1 where several rows match the query.

The query will select one debt and update the database. I would like the linq to return the same result with 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.

Also, you can easily view execution plan of you procedure, and try it to optimize, but with linq query, you cannot easily do this.

AFAIK, IN SQL if you select rows without ORDER BY, it orders the resultset based on the primary key. With Order BY CLAUSE [field], implicitly next order is [primarykey].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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