I know that this topic has been going on for some time, and I went into this or that problem. Until now, I could not find a solution for me that keeps everything together in one place, so the code is still readable.
When creating a user, I want some fields to be set by the object itself through private setters , for example. The GUID and Creation Date, not the "pollution" of 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; } }
Call 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 }; }));
321X May 30 '12 at 20:20 2012-05-30 20:20
source share