问题描述
您能教我更多有关此linq代码如何工作的信息吗? string pass = HashPassword(password)
是一个字符串,HashPassword(password)
也返回一个字符串.
Can you teach me more about how does this linq code work? string pass = HashPassword(password)
is a string, HashPassword(password)
returns a string too.
但是LinQ在比较之前需要一个变量来存储字符串.像这样:
But the LinQ needs a variable to store the string before comparing. Like this:
public bool Login(string email, string password)
{
try
{
string pass = HashPassword(password);
var acc = db.UserAccount.SingleOrDefault(x => x.Email == email && x.HashPassword == pass);
if (acc != null)
{
return true;
}
// email or password is not matched
return false;
}
catch { return false; }
}
和散列密码的方法:
private string HashPassword(string password)
{
return BitConverter.ToString(new SHA256CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(password))).Replace("-", "");
}
自从我更改了行var acc = db.UserAccount.SingleOrDefault(x => x.Email == email && x.HashPassword == pass);
到
var acc = db.UserAccount.SingleOrDefault(x => x.Email == email && x.HashPassword == HashPassword(password));
那是行不通的.为什么?
It wouldn't work. Why?
推荐答案
您的声明:var acc = db.UserAccount.SingleOrDefault(x => x.Email == email && x.HashPassword == HashPassword(password));
导致异常并跳转到catch语句.以下是原因.
Your statement: var acc = db.UserAccount.SingleOrDefault(x => x.Email == email && x.HashPassword == HashPassword(password));
is causing an exception and jumping to the catch-statement. Below is the reason why.
有效地,LINQ不知道如何处理您的函数,而它仅与x.HashPassword == pass
一起工作的原因是因为这只是一个简单的字符串比较.
Effectively LINQ doesn't know how to handle your function and the reason why it works with just x.HashPassword == pass
is because that's just a simple string comparison.
摘录自类似的问答集
这篇关于当将方法转换为字符串时,LinQ无法理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!