Przeglądałem kilka kursów C# tworzonych przez "znane" osoby i przewija się w wielu motyw niepublicznych setterów w klasach modeli.
public class User
{
public Guid Id { get; protected set; }
public string Email { get; protected set; }
public string Password { get; protected set; }
public string Salt { get; protected set; }
public string Username { get; protected set; }
public string FullName { get; protected set; }
public string Role { get; protected set; }
public DateTime CreatedAt { get; protected set; }
public DateTime UpdatedAt { get; protected set; }
protected User()
{
}
public User(Guid userId, string email, string username, string role,
string password, string salt)
{
Id = userId;
SetEmail(email);
SetUsername(username);
SetRole(role);
SetPassword(password, salt);
CreatedAt = DateTime.UtcNow;
}
public void SetUsername(string username)
{
if (!NameRegex.IsMatch(username))
{
throw new DomainException(ErrorCodes.InvalidUsername,
"Username is invalid.");
}
if (String.IsNullOrEmpty(username))
{
throw new DomainException(ErrorCodes.InvalidUsername,
"Username is invalid.");
}
Username = username.ToLowerInvariant();
UpdatedAt = DateTime.UtcNow;
}
//dalszy kod
}
- Jak teraz wypełnić taki model danymi np z bazy?
- W warstwie wyższej czytam sobie dane z bazy i co, za kazdym razem muszę wywołać konstruktor modelu z parametrami (danymi z bazy)?
- W takim przypadku za każdym razem będę miał datę utworzenia jako datę bierzącą a nie tą z bazy?
- Guid muszę za każdym razem przekazać ręcznie w konstruktorze?
- Co jeśli mój model będzie zawierał 50 właściwości, wtedy wszystkie mam wprowadzać jako parametry konstruktora?