Click here to Skip to main content
16,012,759 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to use where in linq
the error says can't implicitly convert type string to xx.modules.Students

What I have tried:

Students student = new Students();
int userId = Convert.ToInt16(InputAPIVM.USERID);
student = db.Students.Where(x => x.UserId == userId).ToString();
Posted
Updated 31-Dec-18 5:00am

That's not Where that causes the problem!
You have declared student as a Students variable:
Students student = new Students();
But your code converts the entire return collection to a string:
db.Students.Where(x => x.UserId == userId).ToString()
and tries to assign that string to the student!

The first thing you need to so is think about what you want to return - and Where returns a collection of items, not a single item. INstead of where, I'd suggest FirstOrDefault[^]:
student = db.Students.FirstOrDefault(x => x.UserId == userId);
Which returns a single value (or null if there are no matches)
This assumes that db.Students is a collection of Student items!
 
Share this answer
 
Comments
NebroProg 31-Dec-18 5:10am    
Ok,
but this query update more than one column because UserId is foreinkey
so FirstOrDefault is returning one row
OriginalGriff 31-Dec-18 5:15am    
That query doesn't update anything!
All it does it return matching rows; it doesn't change any of them.
NebroProg 31-Dec-18 5:20am    
I know but I mean this code must return more than one column
OriginalGriff 31-Dec-18 5:52am    
That code doesn't return "columns" - it returns a single class instance from a collection. If the class contains the "columns" you are interested in, then fine. Otherwise ...
NebroProg 31-Dec-18 6:02am    
ok,
if the code be like this
student = db.Students.FirstOrDefault(x => x.UserId == userId).Select(x =>x.UserId);
what is the error
int userId = Convert.ToInt16(InputAPIVM.USERID);

           student = db.Students.Where(x => x.UserId == userId).ToList();

           if (student != null)
           {
               foreach (Students s in student)
               {
                   s.lat_long = InputAPIVM.LAT_LONG;
                  }
 
Share this answer
 
Comments
Dave Kreskowiak 31-Dec-18 11:08am    
student will never be null. If there are no records to return, the call to .ToList() will create an empty collection, not null. You don't need the check for null at all.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900