I can successfully return a model from my controller like this:
return View(lemonadedb.Messages.ToList() );
It’s interpreted perfectly by my view.
Now I only want to show the messages where Messages.user == Membership.GetUser().ToString().
But when I do this:
return View(lemonadedb.Messages.Where( p => p.user == Membership.GetUser().ToString()).ToList());
I get:
‘LINQ to Entities does not recognize
the method ‘System.String ToString()’
method, and this method cannot be
translated into a store expression.’
I need some way to narrow down the results of the messages table.
Should I use the find() method somehow? I thought it was only for ID’s.
How should I do this?
The reason you’re having this issue is that Entity Framework is trying to evaluate the expression
Membership.GetUser().ToString()into an SQL query. You need to create a new variable to store the value of this expression and pass it into your query. Entity Framework will then just interpret this as you expect.The following should work:
I suspect this is a very common mistake that people make when writing Entity Framework queries.