方法无法转换为商店表达式(LINQ)

时间:2017-06-02 21:57:51

标签: c# asp.net database linq

这是我加密密码的get / set方法:

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password {
    set {
        var emp = db.Employees.Find(2);
        password = EncryptDecrypt.Encrypt(emp.Password, "a15s8f5s6e2s3g1w5");
    }
    get {
        return password;
    }

}

我使用以下代码允许用户登录,我也用它来解密密码:

private Employee slogin;

            using (var db = new Entities())
            {
                var erg = from s in db.Employees
                          where s.LastName.ToString() == model.UserName && s.Password == EncryptDecrypt.Decrypt(model.Password, "a15s8f5s6e2s3g1w5")
                          select s;
                slogin = erg.FirstOrDefault();

            }

每当我运行代码时,我在这里得到一个NotSupportedException:slogin = erg.FirstOrDefault();

  

{“LINQ to Entities无法识别方法'System.String   解密(System.String,System.String)'方法,而这个方法不行   被翻译成商店表达。“}

2 个答案:

答案 0 :(得分:3)

"无法翻译成商店表达式"意思是:我不能从那里做SQL。

以下应该有效,但存储这样的可解密密码当然不是一个好习惯:

var decryptedpassword = EncryptDecrypt.Decrypt(model.Password, "a15s8f5s6e2s3g1w5");

var erg = from s in db.Employees
          where s.LastName == model.UserName 
             && s.Password == decryptedpassword
          select s;

答案 1 :(得分:2)

解密查询之外的密码:

var p=EncryptDecrypt.Decrypt(model.Password, "a15s8f5s6e2s3g1w5");
using (var db = new Entities())
{
            var erg = from s in db.Employees
                      where s.LastName == model.UserName && s.Password == p
                      select s;
            slogin = erg.FirstOrDefault();

}

更简单的方法:

using (var db = new Entities())
{
  slogin = db.Employees.FirstOrDefault(s=>s.LastName == model.UserName && s.Password == p);
}