Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: method cannot be translated into a store expression

I am currently trying to limit which users can access which groups, and am doing this by using linq. My problem occours when I am adding the relevant groups to the view.

The error I keep getting is:

LINQ to Entities does not recognize the method 'System.String GetUserId(System.Security.Principal.IIdentity)' method, and this method cannot be translated into a store expression

This is my code:

  var groupUser = db.GroupUsers.Where(u => u.ApplicationUserId == User.Identity.GetUserId()).Select(gr => gr.GroupId);
  pv.GroupList = db.Groups.Where(g => groupUser.Contains(g.Id)).ToList();
  return View(pv);
like image 269
Seb Avatar asked Nov 29 '22 23:11

Seb


1 Answers

You need to call GetUserId() outside the lambda expression, as Linq to Entities is not able to translate it to corresponding SQL (of course there is no SQL alternative for GetUserId()):

var userId = User.Identity.GetUserId();
var groupUser = db.GroupUsers.Where(u => u.ApplicationUserId == userId)
                             .Select(gr => gr.GroupId);
like image 156
Ehsan Sajjad Avatar answered Dec 09 '22 13:12

Ehsan Sajjad