4
votes

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);
1
Extract User.Identity.GetUserId() into a variable. - Yacoub Massad
This helped! Thanks! - Seb
@YacoubMassad - Post it as an answer. - jewishspiderweb

1 Answers

20
votes

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);