My problem is connected to the extraction method called lambda ( I am using it in C# ). I have a database and in it I have a table called Students and I wonder if I would be able to extract the firstName and lastName of certain student whose ID matches my search.
I have tried a few things so far without any luck.
A bit of code from my last attempt :
var studentName =
context.Student //context is the variable with the entities and Student is the table
.Where(student => student.StudentID == SomeInt) // extract only the one with the chosen ID
.Select(student => student.FirstName) // tryng only to select the wanted field(s)
.ToString() // since I want it to be displayed in a textbox
Currently you're calling Select
on an IQueryable<string>
- your query represents a sequence of student first names, even if it only matches a single one.
If you only want a single name, you can use:
var studentName =
context.Student
.Where(student => student.StudentID == SomeInt)
.Select(student => student.FirstName)
.FirstOrDefault();
Then assuming FirstName
is a string, you don't need ToString()
at all. The value will be null
if there's no student with that ID. Alternatively, you could use Single()
, SingleOrDefault()
, First()
, Last()
or LastOrDefault()
. So for example, you'd then use:
if (studentName == null)
{
// No match found. Return an error or whatever.
}
else
{
// Use studentName
}
(You should only use FirstOrDefault()
if you then check for nullity, or pass it on to something else that does so. Otherwise you can end up with a NullReferenceException
later which is hard to diagnose.)
If you want both the first and last names, you need to change your projection. For example:
var studentName =
context.Student
.Where(student => student.StudentID == SomeInt)
.Select(student => new { student.FirstName, student.LastName })
.FirstOrDefault();
Now the type of studentName
will be an anonymous type - again, it'll be null if there are no matches, but otherwise it will have appropriate FirstName
and LastName
properties.
See more on this question at Stackoverflow