简体   繁体   中英

if only one record is return linq output is wrong c#

following code will return newly inserted records id from my Device table.

var newIds = context.Devices.Take(deviceDataList.Count)
                    .OrderByDescending(t => t.Id)
                    .Select(t => t.Id)
                    .ToList();

if deviceDataList.Count is more than 1 it works fine.

but when it is only one it is returning wrong first id instead latest inserted.

First order and then take. Take retrieves the records by the order they are in the collection (perhaps just in the disk or any other reasoning of the database). If you want to be sure it is by the Id then do so.

var result = context.Devices.OrderByDesending(t => Id)
                    .Take(deviceDataList.Count)
                    .Select(t => t.Id);

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