我有一个类,我想使用Fluent NHibernate定义一个唯一的键。我想我已经正确完成了这个,但是我的单位测试中,我保存了两个具有相同字段值的对象,保存了两个项目而没有错误。这就是我所拥有的:
映射覆盖:
public class ItemOverride : IAutoMappingOverride<Item>
{
#region IAutoMappingOverride<Item> Members
public void Override(AutoMapping<Item> mapping)
{
mapping.Map(t => t.Prompt).UniqueKey("UIX_Item_Prompt").Not.Nullable();
}
#endregion
}
单元测试
[Test]
public void CannotSaveDuplicateItemPrompt()
{
ServiceLocatorInitializer.Init();
IItemManagementService itemManagementService = new ItemManagementService(repository);
Item first = ItemInstanceFactory.CreateValidTransientItem();
first.Prompt = "Duplicate";
itemManagementService.SaveOrUpdate(first);
Item second = ItemInstanceFactory.CreateValidTransientItem();
second.Prompt = "Duplicate";
ActionConfirmation confirm = itemManagementService.SaveOrUpdate(second);
Assert.IsFalse(confirm.WasSuccessful);
Assert.AreEqual(confirm.Message, "");
}
答案 0 :(得分:0)
好的,如果我将两个保存包装在一个事务中,它就可以工作。这是新的单元测试:
[Test]
[ExpectedException(typeof(GenericADOException))]
public void CannotSaveDuplicateItemPrompt()
{
ServiceLocatorInitializer.Init();
IItemManagementService itemManagementService = new ItemManagementService(repository);
NHibernateSession.Current.BeginTransaction();
Item first = ItemInstanceFactory.CreateValidTransientItem();
first.Prompt = "Duplicate";
itemManagementService.SaveOrUpdate(first);
Item second = ItemInstanceFactory.CreateValidTransientItem();
second.Prompt = "Duplicate";
ActionConfirmation confirm = itemManagementService.SaveOrUpdate(second);
NHibernateSession.Current.Transaction.Commit();
}