Linq To Entities exception does not recognize the method and cannot be translated into store expression
Can somebody please give an explanation to why I am getting this error with my LINQ code?
LINQ to Entities does not recognize the method 'System.String GenerateHashWithSalt(System.String, System.String)'method and this method cannot be translated into a store expression.
var query = (from u in context.Users
where
u.Passwo开发者_运维知识库rd ==
GenerateHashWithSalt(password, GetUserID(username))
select u).Count();
You are trying to pass a method to EF which tries to convert that method to known SQL command.
SQL doesn't know about GenerateHashWithSalt(System.String, System.String)
You should first assign the result to a variable then generate your Linq to Entity Query.
Example
var hashedPassword = GenerateHashWithSalt(password, GetUserID(username));
var user = (from p in Users
where p.Password == hashedPassword
select p).FirstOrDefault();
LINQ providers look at your expression tree, and try to generate equivalent TSQL (etc) from that. This only works for recognised methods, or recognised expression scenarios.
It can't look at an arbitrary method in your C# code and execute that at the database.
However! You could simplify the query for it:
var hash = GenerateHashWithSalt(password, GetUserID(username);
var count =context.Users.Count(u => u.Password == hash);
It looks like it's a shortcoming of LINQ to Entities
As Jethro says, and the link above shows an example, you need to convert it to something that SQL knows about.
精彩评论