定做非基本类型我有这样的自定义类型:在实体框架代码优先4.1
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();
}
}
所以,我想在恩我的实体框架项目中使用此类型。我如何将类型映射为像字符串一样工作。
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public PasswordString Password { get; set; }
}
的使用示例:
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实现吗?
这是一种非常不安全的身份验证方法。不要重新进行身份验证。使用可用的现成供应商。你可能想阅读[这个使用非常相似的计划制作全国新闻的公司的故事。](http://arstechnica.com/tech-policy/news/2011/02/anonymous-speaks-the-inside-story -of-the-hbgary-hack.ars/2) –
我无法回答这个问题,但你可能想查看[Ado.Net Entity Framework Membership Provider](http://efmembership.codeplex.com/)并节省一些时间。 – Chris