NHibernate UniqueKey 未强制执行
我有一个类,我想使用 Fluent NHibernate 定义一个唯一的键。我认为我已经正确完成了此操作,但是我的单元 tes,t 在其中为相关字段保存了两个具有相同值的对象,保存了这两个项目而没有错误。这就是我所得到的:
映射覆盖:
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, "");
}
I have a class on which I'd like to define a unique key using Fluent NHibernate. I think I've done this correctly, but my unit tes,t in which I save two objects with the same value for the field in question, saves both items without error. Here's what I've got:
Mapping override:
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
}
Unit Test
[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, "");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,如果我将两个保存包装在一个事务中,它就可以工作。这是新的单元测试:
Okay, it works if I wrap the two saves in a transaction. Here's the new Unit Test: