views:

19

answers:

1

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, "");
}

Thanks!

A: 

Okay, it works if I wrap the two saves in a transaction. Here's the new Unit Test:

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

related questions