【发布时间】:2015-09-02 02:03:20
【问题描述】:
你能告诉我更多关于这个 linq 代码是如何工作的吗? string pass = HashPassword(password) 是一个字符串,HashPassword(password) 也返回一个字符串。
但是 LinQ 在比较之前需要一个变量来存储字符串。像这样:
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));
这行不通。为什么?
【问题讨论】:
-
您收到的错误是什么?
-
@Kevin 如果您使用 Linq2objects 以外的其他东西,如 EF、Linq2DB 等,Linq 提供程序将无法将
HashPassword(password)转换为 sql 代码(它无法转换为 sql stmt) .您的第一个版本只是一个简单的字符串比较 (WHERE EMAiL=@SOMEVAR)。 -
所以,它返回的是 false,而不是真正的错误?
-
在你的 catch 语句上放置一个断点,它会告诉你为什么它每次都返回 false。
-
因为@Eser 所说:LINQ 提供程序无法翻译您的 HashPassword 函数。您收到的异常将显示一条消息。