2011-07-22 227 views
1

定做非基本类型我有这样的自定义类型:在实体框架代码优先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实现吗?

+5

这是一种非常不安全的身份验证方法。不要重新进行身份验证。使用可用的现成供应商。你可能想阅读[这个使用非常相似的计划制作全国新闻的公司的故事。](http://arstechnica.com/tech-policy/news/2011/02/anonymous-speaks-the-inside-story -of-the-hbgary-hack.ars/2) –

+0

我无法回答这个问题,但你可能想查看[Ado.Net Entity Framework Membership Provider](http://efmembership.codeplex.com/)并节省一些时间。 – Chris

回答

2

实体框架不支持类型转换器或任何其他方式将简单数据库列映射到您的自定义类型,并且此功能甚至尚未计划用于下一版本。所以你的问题的答案是:不可能。

1

在LINQ to Entities查询中,不能将类(或结构)用作复杂类型。我为了执行这个比较...

u.Password == "apple" 

...构造函数必须被调用反过来MD5.CalculateMD5Hash其中要求。此方法无法转换为SQL,查询将引发异常。 LINQ to Entities很可能不支持任何重载的操作符(如==) - 出于同样的原因:EF无法将其转换为SQL。

相关问题