如何在NHibernate中通过代码映射一个字段值对象
本文关键字:一个 字段 对象 映射 NHibernate 代码 | 更新日期: 2023-09-27 18:21:15
我有一个Account
类,它包含Email
、Firstname
、Lastname
和PasswordHash
我想为Email
和PasswordHash
创建值对象,并在构造函数上使用正则表达式来消除纯字符串,并确保这些字段包含有效数据,但我被问到,如何通过NHibernate持久化这个Account
实体
我如何指示NHibernate将这些值作为字符串存储在数据库中,但在我请求时将其恢复为值对象
我必须为它编写DTO并前后映射它吗?或者有更好的方法吗?
域模型:
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映射:
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());
}
}