Neo
Neo

Reputation: 16219

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.

Upvotes: 0

Views: 61

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

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);

Upvotes: 3

Related Questions