开发者

Returning an EF model class

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 thi开发者_如何学Cs?


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:

var user = Membership.GetUser().ToString();
return View(lemonadedb.Messages.Where(p => p.user == user).ToList());

I suspect this is a very common mistake that people make when writing Entity Framework queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜