我知道这个话题已经持续了一段时间,我也遇到了同样的问题。到目前为止,我还没有找到一种解决方案,可以将整个东西放在一个地方,这样代码仍然可读。
在创建用户时,我希望通过对象本身设置一些字段private setters
,例如 GUID 和创建日期,而不是“污染”构造函数。
我的用户类:
public class User
{
public static User Create(Action<User> init)
{
var user = new User();
user.Guid = Guid.NewGuid();
user.Since = DateTime.Now;
init(user);
return user;
}
public int UserID { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual ICollection<Widget> Widgets { get; set; }
[StringLength(50), Required]
public string Name { get; set; }
[EmailAddress, Required]
public string Email { get; set; }
[StringLength(255), Required]
public string Password { get; set; }
[StringLength(16), Required]
public string Salt { get; set; }
public DateTime Since { get; private set; }
public Guid Guid { get; private set; }
}
调用代码:
context.Users.Add(User.Create(c=>
{
c.Name = "Name";
c.Email = "some@one.com";
c.Salt = salt;
c.Password = "mypass";
c.Roles = new List<Role> { adminRole, userRole };
}));