目前我正在使用以下代码
var lastId = DataRepository.All().ToList().LastOrDefault().Id;
以便找到最后插入的行Id
如何在不投射到ToList()
的情况下重构上面的代码?
DataRepository.All()
返回IQuerable<T>
答案 0 :(得分:1)
这与HashPsi评论一样简单。
如果您的DataRepository.All()
返回IQuerable<T>
- 所有这些类型的查询都会导致一个简单的SQL语句只返回最后一个 ID :
// query
IQueryable<T> query = DataRepository.All();
// just MAX
var maxIdA = query
.Max(x => x.Id);
// also this kind of construct with Take() and SingleOrDefault()
// will be effective (not loading complete list from DB to app)
// and could be used for more complex queries with unique result
var maxIdB = query
.OrderByDescending(x => x.Id)
.Select(x => x.Id)
.Take(1)
.SingleOrDefault();