Linq To Entities exception does not recognize the method and cannot be translated into a storage expression

Can someone please explain why I am getting this error with my LINQ code?

LINQ to Entities does not recognize the 'System.String GenerateHashWithSalt (System.String, System.String) method and this method cannot be translated into a storage expression.

var query = (from u in context.Users where u.Password == GenerateHashWithSalt(password, GetUserID(username)) select u).Count(); 
+4
source share
3 answers

You are trying to pass an EF method that is trying to convert this method to a known SQL command. SQL does not know about GenerateHashWithSalt(System.String, System.String)
You must first assign the result to a variable, and then generate a Linq to Entity Query query.

Example

 var hashedPassword = GenerateHashWithSalt(password, GetUserID(username)); var user = (from p in Users where p.Password == hashedPassword select p).FirstOrDefault(); 
+12
source

LINQ providers look at your expression tree and try to generate an equivalent TSQL (etc.). This only works for recognized methods or scripts for recognized expressions.

It cannot look at an arbitrary method in your C # code and execute it in the database.

But! You can simplify the request for it:

 var hash = GenerateHashWithSalt(password, GetUserID(username); var count =context.Users.Count(u => u.Password == hash); 
0
source

This seems to be a LINQ flaw for entities

As Jethro says, and the link above shows an example, you need to convert it to what SQL knows about.

0
source

All Articles