Reputation: 107
Id | StName | Subject |
1 | Tom | Math |
2 | Jerry | Science |
I am new in LINQ and I am trying to get only Id
of StName
Jerry from database using LINQ but I couldn't.
[HttpGet]
public IEnumerable<StudentModel> GetStudentId()
{
var id = _context.StudentModel.OrderBy(a => a.Id).ToList();
return(id);
}
but I got all the data. I want to get the latest recorded id (only id).
Upvotes: 1
Views: 2471
Reputation: 22485
You could try below code.
[HttpGet]
public int GetStudentId()
{
var id = _context.StudentModel.OrderByDescending(a => a.Id).FirstOrDefault();
return id.Id;
}
Also You could write some like below:
[HttpGet]
public int GetStudentId()
{
var id = _context.StudentModel.Max(a => a.Id).FirstOrDefault();
return id.Id;
}
Note: The things you have to do is, need to filter max or top entry of database entity then return it. I have done that as well.
Upvotes: 2
Reputation: 17578
Right now you're getting a list of all records in your database table. You only want the first one when ordered by the Id in descending order.
[HttpGet]
public int GetStudentId()
{
var latestStudentRecord = _context.StudentModel
.OrderByDescending(a => a.Id)
.First();
// return only the Id property of the latest record
return latestStudentRecord.Id;
}
Note, this will only work if your Id's are sequential, and it's guaranteed that the "latest" record will always have the highest Id value.
Later on, you might want to swap First()
to FirstOrDefault()
, in the case where your table has no records.
The method signature has been changed to return only an int rather than the whole list.
Upvotes: 5
Reputation: 155
Change method to return same type as your Id, then fetch just first item of the collection and return its property Id.
This should be the case.
public int GetStudentId()
{
var student = _context.StudentModel.OrderBy(a => a.Id).FirstOrDefault();
return student.Id;
}
Upvotes: 0