In the following code, I am trying to get a profile for the user that is currently logged in.
Dim userProfile = db1.UserProfiles.Where(Function(p) p.UserId = Membership.GetUser.ProviderUserKey).Single
The error is “LINQ to Entities does not recognize the method ‘System.Object CompareObjectEqual(System.Object, System.Object, Boolean)’ method, and this method cannot be translated into a store expression.”
Does anyone know what’s wrong with this, or is there a better way… And, how can I make this more secure; i.e. add a condition if no record is found?
I am using VB ASP.NET MVC 3.
Thank you.
Edit:
Here’s my new code:
Dim db1 As UserProfileDbContext = New UserProfileDbContext
Dim user = Membership.GetUser()
Dim key As Guid = user.ProviderUserKey
Dim finalKey = key.ToString
Dim userProfile = db1.UserProfiles.Where(Function(p) p.UserId = finalKey).Single
Dim companyId = userProfile.CompanyId
L2E is trying to render your lamba expression
(p) p.UserId = Membership.GetUser.ProviderUserKeyin to an SQL Expression which it can use to hit the database.However,
Membership.GetUser()is a .NET method. L2E is complaining that it doesn’t know how to render this method in to SQL syntax.Try this instead:
edit: MembershipUser.ProviderUserKey is a CLR
Object. SQL can’t compare two objects, so you’ll need to strong type it before running the expression. For example, if your user key is aString:This should work better because a simple equality expression
=is understood by L2E and can be rendered in to an equivilent SQL expression, something like:SELECT * FROM Profiles WHERE UserId = @Argument, where the @Argument is supplied by entity framework.Also as an aside, L2E will group chained calls until the end, so an expression like:
db1.UserProfiles.Skip(10).Take(30).Where(Function(p) p.UserId = Membership.GetUser.ProviderUserKey)… would still fail, because L2E will combine the
SkipTakeandWherecomponents in to a single SQL expression. You can force L2E to hit the server by callingToArrayToListorToDictionary. That expression could be made valid by changing it to:db1.UserProfiles.Skip(10).Take(30).ToArray().Where(Function(p) p.UserId = Membership.GetUser.ProviderUserKey)The
ToArrayforces the execution of the SQL statement, giving you a .NET Array which does support complex lambas.