首页 > 解决方案 > 如果只有一条记录返回 linq 输出是错误的 c#

问题描述

id以下代码将从我的Device表中返回新插入的记录。

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

如果deviceDataList.Count超过1它工作正常。

但是当它只有一个时,它首先返回错误id而不是最新插入。

标签: c#entity-frameworklinq

解决方案


先点菜再拿。Take按记录在集合中的顺序检索记录(可能只是在磁盘中或数据库的任何其他推理中)。如果你想确定它是Id那么做。

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

推荐阅读