简体   繁体   English

如何使用EntityFramework建立Rich Domain模型

[英]How to build Rich Domain Model with EntityFramework

Im using Entity Framework 4.2 (Code First) to create my database, which works fine so far,but now im facing a problem that is very easy to overcome in Hibernate or JPA but im not able see it here. 我使用Entity Framework 4.2(代码优先)创建我的数据库,到目前为止,它可以正常工作,但是现在我遇到了一个非常容易在Hibernate或JPA中克服的问题,但是我在这里看不到它。

I have define a User object which have a property called Password, i want to customize the {get;set;} operations in order to have certain logic when setting the password (i want to stored a hash version of it, but i want that logic inside my domain object ala DDD). 我定义了一个User对象,该对象具有名为Password的属性,我想自定义{get; set;}操作,以便在设置密码时具有某些逻辑(我想存储它的哈希版本,但是我想要域对象ala DDD中的逻辑)。 But im facing that when materializing an object from the database my setter is being called and is not using directly the private field. 但是我面对的是,当从数据库中实现对象时,将调用我的setter,而不是直接使用私有字段。

Im trying to build a Rich Domain Object model and avoiding DAO/Repository pattern on this. 我试图建立一个丰富的域对象模型,并避免使用DAO /存储库模式。

Is this possible thru Entity Framework, or will i be force to use DAO/Repository patterns. 是通过实体框架实现的,还是我将被迫使用DAO /存储库模式。

Below is an extraction of my User object: 以下是我的User对象的摘录:

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;

    }

} }

Start by adding an encrypted passwordstring value object (immutable) 首先添加一个加密的密码字符串值对象(不可变)

for instance 例如

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
  }
}

In EF it is called a complex type 在EF中称为复杂类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM