2010-08-06 75 views
0

我有一個類,我想用Fluent NHibernate來定義一個唯一的鍵。我認爲我已經正確地做了這件事,但是我的單位測試中,我保存了兩個具有相同字段值的對象,並保存了這兩個項目沒有錯誤。下面是我得到了什麼:NHibernate的UniqueKey沒有被強制執行

映射覆蓋:

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

好吧,如果我換了兩個交易節省了它的工作原理。這裏是新的單元測試:

[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(); 
    }