简体   繁体   中英

Get Last N Element From Entity by LINQ

I want to find the last primary id of a table. Table Name: table1 columns: Id, name, age

var id = _db.table1.OrderByDescending(x => x.Id).FirstOrDefault().Id

The above query is causing performance problem when records exceed 100 000 records. How to improve the performance?

假设 _db.Table1 是可查询的,您可以尝试以下操作:

var id = _db.table1.Max(e => e.Id);

If performance is an issue you could issue a raw query against the database:

int id = _db.table1.SqlQuery<int>("SELECT MAX([Id]) FROM dbo.table1").FirstOrDefault<int>();

Entity Framework Raw SQL Queries: https://msdn.microsoft.com/en-us/library/jj592907%28v=vs.113%29.aspx

It doesn't get any faster than this as far as the selection of data is concerned.

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