views:

21

answers:

1

Could someone explain this for me?

I have standard relations in my MSSQL DB:

[item]
id
symbol

[item_version]
id
item_id (fk)
symbol

In [item] mapping there is a standard item_version BAG with cascade="all" and many-to-one in [item_version] mapping.

This is the test case:

    [Test]
    public void AddNewVersionToPersistentObject()
    {
        //creating item
        Item i = new Item();
        i.Symbol = "Item 1 symbol";    

        //saving item
        Item.Dao.Save(i);
        long id = i.Id;

        //clearing session and getting item back from DB
        DataHelper.DaoFactory.ClearSession();
        Item itemFromDb = Item.Dao.GetById(id);

        //creating new versions
        ItemVersion v1 = new ItemVersion();
        v1.Symbol = "version 1 symbol";

        ItemVersion v2 = new ItemVersion();
        v2.Symbol = "version 2 symbol";

        //adding versions and saving item
        itemFromDb.AddItemVersion(v1);
        itemFromDb.AddItemVersion(v2);
        Item.Dao.SaveOrUpdate(itemFromDb);


        //clearing session, getting back item and checking results
        DataHelper.DaoFactory.ClearSession();
        Item itemFromDb2 = Item.Dao.GetById(id);
        Assert.AreEqual(2, itemFromDb2.ItemVersions.Count);
    }

Test fails, when I adding NEW ItemVersion objects to Item object taken from DB (as coded above).

When I add new ItemVersions to new Item, and call Save on Item - everything works fine. Why is that?

A: 

Save/Update/Delete/etc methods do not persist changes to the database; they only queue certain actions in the unit of work (the session)

In fact, you don't even need to call any of them to modify persistent objects: that happens automatically on Flush (which, BTW, you shouldn't call explicitly: use a transaction instead)

More info: http://nhforge.org/doc/nh/en/index.html#manipulatingdata

Diego Mijelshon
Thanks, now I've got the point :)
Adam