Reputation: 14155
Currently I'm using following code
var lastId = DataRepository.All().ToList().LastOrDefault().Id;
in order to find last inserted row Id
How can I refactor above code without projecting into ToList()
?
DataRepository.All()
returns IQuerable<T>
Upvotes: 1
Views: 331
Reputation: 123861
It is really as easy as a HashPsi comment.
In case that your DataRepository.All()
returns IQuerable<T>
- all these kinds of queries will result in one simple SQL statement returning just the last 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();
Upvotes: 1