2011-11-04 33 views
2

使用Entity Framework 4.2(代碼優先)創建我的數據庫,目前工作正常,但現在我面臨的問題很容易在Hibernate或JPA中克服,但我不是能夠在這裏看到它。如何使用EntityFramework構建豐富域模型

我已經定義了一個User對象,它具有一個名爲Password的屬性,我想定製{get; set;}操作以在設置密碼時擁有某些邏輯(我想存儲它的哈希版本,但我想在我的域對象阿拉德DDD邏輯)。但即時通信面臨的情況是,從數據庫實現對象時,我們的setter被調用並且不直接使用私有字段。

我試圖建立一個富域對象模型,並避免DAO/Repository模式。

這是可能通過實體框架,或者我會強制使用DAO /存儲庫模式。

下面是我的用戶對象的提取:

public class User 
{ 
    [Key] 
    public string LoginId { get; set; } 

    [Required] 
    private string password; 

    public string Password 
    { 
     get { return password; } 
     set { 
      //Random Salt 
      byte[] s; 
      using (RNGCryptoServiceProvider prov = new RNGCryptoServiceProvider()) 
      { 
       s = new byte[20]; 
       prov.GetBytes(s); 
      } 
      this.salt = Convert.ToBase64String(s); 
      //Random salt     
      password = ComputeHash(value); 
      } 
    } 

    [Required] 
    private string salt; 
    public string Salt { 
         get { return this.salt; } 
         set { throw new InvalidOperationException("Salt is not an assignable property. Assign a password first to your model and a Salt will get created."); } 
         } 

    public bool ValidatePassword(string clearTextPassword) 
    { 
     return this.Password == this.ComputeHash(clearTextPassword); 
    } 
    public string ComputeHash(string value) 
    { 
     ... 
     return hashVersion of value; 

    } 

}

+0

我忍不住想說這個答案:「爲了構建一個豐富的DM,你首先需要一個豐富的領域。 Aquire this,你將在所有的事情上都取得成功' – Jeremy

+0

感謝你的想法,我只是舉了一個很短的例子,或者我只是用了錯誤的措辭(豐富的DM),但把它放在一邊,回到原來的位置題。在EntityFramework中是否可以自定義{get; set;}並讓EntityFramework直接將其邏輯映射到私有字段,而不要調用公共屬性? – jcgarciam

+0

我發現了以下內容:(如何在「getter」或「setter」之後編寫自定義邏輯?)但在本文的鏈接中會引發404 :(http://blogs.msdn.com/b/dsimmons/archive/ 2008/08/10/EF-FAQ-實體classes.aspx – jcgarciam

回答

0

開始通過將加密passwordstring值對象(不可變)

例如

public class EncryptedString 
{ 
    public string Value { get;private set; } 
    public string Hash { get;private set; } 
    bool Validate(string password); 

    public Encrypted(string value) 
    { 
    // Put logic here 
    } 
} 

在EF它被稱爲複合型