我有一个账户模型对象和对账户名称的唯一约束。在域驱动设计中,如果使用nHibernate,我应该如何在之前检查名称的唯一性?如何在保存前检查nHibernate和DDD中的唯一约束违规?
我不想依赖nHibernate异常来捕获错误。我想向我的用户返回一个比晦涩难懂的错误消息could not execute batch command.[SQL: SQL not available]
在问题Where should I put a unique check in DDD?中,有人建议使用像这样的规范。
Account accountA = _accountRepository.Get(123);
Account accountB = _accountRepository.Get(456);
accountA.Name = accountB.Name;
ISpecification<Account> spec = new Domain.Specifications.UniqueNameSpecification(_accountRepository);
if (spec.IsSatisfiedBy(accountObjA) == false) {
throw new Domain.UnicityException("A duplicate Account name was found");
}
与规格代码:
public bool IsSatisfiedBy(Account obj)
{
Account other = _accountRepository.GetAccountByName(obj.Name);
return (other == null);
}
这适用于刀片,但不这样做,因为更新的时候。我试过的代码更改为:
public bool IsSatisfiedBy(Account obj)
{
Account other = _accountRepository.GetAccountByName(obj.Name);
if (obj == null) { // nothing in DB
return true;
}
else { // must be the same object.
return other.Equals(obj);
}
}
是,当执行GetAccountByName()
恢复可能重复NHibernate的会发出一个更新到数据库的问题...
return session.QueryOver<Account>().Where(x => x.Name == accntName).SingleOrDefault();
所以,我应该怎么做?规范不是正确的做法吗?
感谢您的想法!
谢谢Thilak,我会看看'ISQLExceptionConverter'。我发现[此博客文章](http://fabiomaulo.blogspot.com/2009/06/improving-ado-exception-management-in.html)和[这个其他问题](http://stackoverflow.com/questions/1524167/custom-exception-using-nhibernate-isqlexceptionconverter)来帮助'ISQLExceptionConverter' – dstj