[英]Adding and saving not persistent objects to persistent object in NHibernate
Could someone explain this for me? 有人可以帮我解释一下吗?
I have standard relations in my MSSQL DB: 我在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. 在[item_version]映射中,有一个标准的item_version BAG,它带有cascade =“ all”,并且是多对一的。
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). 当我将新的 ItemVersion对象添加到从数据库获取的Item对象中时,测试失败(如上所述)。
When I add new ItemVersions to new Item, and call Save on Item - everything works fine. 当我将新的ItemVersions添加到新的Item并调用Save on Item时,一切正常。 Why is that?
这是为什么?
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) 实际上,您甚至不需要调用它们中的任何一个来修改持久对象:这在Flush上自动发生(顺便说一句,您不应该显式调用:而是使用事务)
More info: http://nhibernate.info/doc/nh/en/index.html#manipulatingdata 更多信息: http : //nhibernate.info/doc/nh/en/index.html#manipulatingdata
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.