I know this topic is going on for a while and I walked into some kind of the same issue. So far I couldn t find a solution for me that keeps the whole thing together at one place so the code is still readable.
At creation of an user I want to have some fields set by the object itself via private setters
, e.g. a GUID and Creation Date and not polluting the constructor.
My User class:
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; }
}
Calling code:
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 };
}));