I have an Account
class, which contains Email
, Firstname
, Lastname
and PasswordHash
.
I want to create Value-Objects for Email
and PasswordHash
, And using regular expressions on constructors to get rid of plain strings and be sure that these fields contain valid data, but I'm questioned, how to persist this Account
entity via NHibernate?
How can I instruct NHibernate to store this values as strings in database, but to restore it as Value-Objects when I ask for it?
Do I have to write DTO's for it and map it back and forward or is there a better way?
Asked
Active
Viewed 552 times
1
-
1If you think that this is a task for data layer, use Custom Type... – Radim Köhler Nov 08 '15 at 14:08
-
Possible duplicate of [Separate table for Value Objects on NHibernate](https://stackoverflow.com/questions/1331178/separate-table-for-value-objects-on-nhibernate) – shA.t Sep 02 '17 at 05:01
1 Answers
1
Domain Model:
public class Email: ValueObjectBase<Email>
{
private readonly string _address;
public Email(string address)
{
_address = address;
Validate(); //check RegX
}
}
public class FullName: ValueObjectBase<FullName>
{
private readonly string _firstName;
private readonly string _lastName;
public FullName(string firstName, string lastName)
{
_firstName = firstName;
_lastName = lastName;
this.Validate();
}
public string FirstName { get { return _firstName; } }
public string LastName { get { return _lastName; } }
}
public class Account : EntityBase<Guid>, IAggregateRoot
{
public virtual FullName FullName { get; set; }
public virtual Email Email { get; set; }
}
NHibernate Mapping:
public class AccountMap : ClassMap<Account>
{
public AccountMap()
{
LazyLoad();
Id(c => c.Id).GeneratedBy.Assigned();
Component(c => c.FullName, m =>
{
m.Map(Reveal.Member<FullName>("_firstName")).Column("FirstName").Length(30).Not.Nullable();
m.Map(Reveal.Member<FullName>("_lastName")).Column("LastName").Length(40).Not.Nullable();
});
Component(c => c.Email, m => m.Map(Reveal.Member<Email>("_address")).Column("EmailAddress").Not.Nullable());
}
}

Mohammad Radman Far
- 137
- 1
- 8