c# - Single field extraction from a database using lambda -
My problem is related to the extraction method called lambda (I am using it in C #). I have a database and I have a table of students in it and I wonder if I would like to remove the name and last name of such a student whose ID matches my search.
I have tried some things away without any luck.
Some codes with my last attempt:
var studentName = context.Student // context is the variable and student table with the table. Where (student => student student id == few instances) // Only remove one with the selected ID. Selection (student = & gt; student.pasteurname) // Tryng only to select the desired field. Toastring () // When I want to display it in a text box
Currently you can enter ' IQueryable & lt; String & gt; Calling on - Your query represents the first name of a student sequence , even if it only matches one.
If you want only one name, you can use it:
var stu DentName = context student. Where (student => student student ID == some int). Select (student = & student; first name). FirstOver Default (); Then assume that first name is a string, you do not need ToString () . This value is null < / Code> If there is no student with that ID Alternatively, you can enter single () , SingleOrDefault () , first () , last () or LastOrDefault () . For example, you would use it:
if (studentName == tap) {// no match was found. An error or whatever you return} Other {// Username}} (You can only use FirstOrDefault () , if you check continuity Do it, or pass it on to something else otherwise you can end up with a NullReferenceException which is hard to diagnose.)
If both of you first and Both want the last name, so you need to change your projection for example:
var studentName = contextstudent. Where (student = & gt; student student id == some). Select (student = & gt; new {student.FirstName, student.LastName}) .FirstOrDefault (); The type of studentName will now be an anonymous type - again, if there are no matches, it will be empty, but otherwise it would be appropriate first Name and last name properties.
Comments
Post a Comment