C# – Linq: method cannot be translated into a store expression

.netc++linqlinq-to-entitiesvisual-studio-2010

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

Best Solution

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