gpt4 book ai didi

NHibernate ISession.Save() - 为什么这会立即持久化我的实体?

转载 作者:行者123 更新时间:2023-12-04 21:54:15 25 4
gpt4 key购买 nike

我正在使用 NHibernate 创建大量实体,将它们附加到我的 ISession,然后使用事务将我的更改提交到数据库。代码示例如下:

ISession _context = SessionProvider.OpenSession();

//Create new entities
for(int i=0; i<100; i++)
{
MyEntity entity = new MyEntity(i);

//Attach new entity to the context
_context.Save(entity);
}

//Persist all changes to the database
using(var tx = _context.BeginTransaction())
{
//Flush the session
tx.Commit();
}

我的印象是 _context.Save() 行只是让 ISession 知道新实体,但在我通过 tx.Commit() 行刷新 session 之前,不会将任何更改保留到数据库中。

但我观察到的是,每次我调用 _context.Save() 时,数据库都会获得一个新实体。结果,我最终对数据库进行了太多的单独调用。

有谁知道为什么 ISession.Save() 会自动持久化更改?我是否误解了 NHibernate 的行为方式?谢谢。

***编辑 - 只是为了澄清(根据两个建议的答案) - 我的问题是,一旦我调用 _context.Save(),数据库就会更新。我不希望这会发生。在调用 tx.Commit() 之前,我不希望将任何内容插入到数据库中。不幸的是,到目前为止,这两个建议的答案都没有帮助解决这个问题。

可以在 here 找到一些关于身份生成器的好信息。

最佳答案

尝试:

using(Session _context = SessionProvider.OpenSession())
using(var tx = _context.BeginTransaction())
{
//Create new entities
for(int i=0; i<100; i++)
{
MyEntity entity = new MyEntity(i);

//Attach new entity to the context
_context.Save(entity);
}

//Flush the session
tx.Commit();
}

关于NHibernate ISession.Save() - 为什么这会立即持久化我的实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6485083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com