Passwords 实体框架代码first 4.1中的自定义非原语类型
我有这个自定义类型:Passwords 实体框架代码first 4.1中的自定义非原语类型,passwords,entity-framework-4.1,code-first,custom-type,Passwords,Entity Framework 4.1,Code First,Custom Type,我有这个自定义类型: public struct PasswordString { private string value; public PasswordString(string value) { this.value = MD5.CalculateMD5Hash(value); } public string Value { get { return this.value; } set {
public struct PasswordString
{
private string value;
public PasswordString(string value)
{
this.value = MD5.CalculateMD5Hash(value);
}
public string Value
{
get { return this.value; }
set { this.value = MD5.CalculateMD5Hash(value); }
}
public static implicit operator PasswordString(string value)
{
return new PasswordString(value);
}
public static implicit operator string(PasswordString value)
{
return value.Value;
}
public static bool operator ==(string x, PasswordString y)
{
return x.CompareTo(y) == 0;
}
public static bool operator !=(string x, PasswordString y)
{
return x.CompareTo(y) != 0;
}
public override string ToString()
{
return Value;
}
}
public static class MD5
{
public static string CalculateMD5Hash(string input)
{
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
使用示例:
User user = new User()
{
Username = "steve",
Password = "apple"
};
System.Console.WriteLine(user.Password == "apple");
System.Console.WriteLine(user.Password);
此代码生成:
True
1F3870BE274F6C49B3E31A0C6728957F
我的目标是对实体框架进行查询,以获得如下内容:
var q = from u in users
where u.Username == "steve" && u.Password == "apple"
orderby u.Username
select u;
因此,我不需要加密密码,但它将被加密存储在数据库中
我试图用EF使用这个类,但没有成功。使用Entity Framework 4.1可以实现这一点。在LINQ to Entities查询中,不可能将类(或结构)用作复杂类型。我命令执行此比较
u.Password == "apple"
。。。必须调用构造函数,构造函数依次调用
MD5.CalculateMD5Hash
。无法将此方法转换为SQL,查询将引发异常。LINQ to Entities甚至可能不支持任何重载运算符(如=
)——原因相同:EF无法将其转换为SQL。Entity framework不支持类型转换器或任何其他将简单数据库列映射到自定义类型的方法,下一版本甚至还没有计划使用这种功能。所以你的问题的答案是:不可能 这是一种非常不安全的身份验证方法。不要重新发明身份验证。使用可用的现成提供程序。你可能想阅读我不能回答这个问题,但你可能想看看,节省一些时间。
u.Password == "apple"