当将方法转换为字符串时,LinQ无法理解 [英] LinQ cannot understand when converting a method to a string

查看:41
本文介绍了当将方法转换为字符串时,LinQ无法理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能教我更多有关此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 2 SQL将查询转换为表达式树,然后将该表达式树转换为SQL.由于您的自定义函数没有与SQL相关的函数,因此它不知道如何翻译它并引发异常. -大卫·费弗(David Pfeffer)

LINQ 2 SQL is converting your query into an expression tree, and then translating that expression tree into SQL. Since your custom function doesn't have an SQL correlated function, it doesn't know how to translate it and throws an exception. - David Pfeffer

这篇关于当将方法转换为字符串时,LinQ无法理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆