简体   繁体   English

保存时的NHibernate FlushMode

[英]NHibernate FlushMode on Save

I have set the FlushMode property on an NHibernate session to FlushMode.Never, but when I call session.Save(User), a call gets made to the database anyway. 我已经将NHibernate会话上的FlushMode属性设置为FlushMode.Never,但是当我调用session.Save(User)时,无论如何都会调用数据库。 Is this how this is supposed to work? 这是怎么回事? I would think that it shouldn't do an insert until I call Flush(). 我认为在调用Flush()之前不应该插入。

Edit: I found the issue, I changed the primary key to guid and it worked. 编辑:我发现了问题,我将主键更改为guid并且工作正常。 Are there any other types (ie no guid primary key) that will work? 是否有其他类型(即没有guid主键)可以工作? I would rather have a number instead of a guid... 我宁愿有一个数字而不是一个guid ......

You were using a native generator, right? 你使用的是原生发电机,对吧?

The problem with this lies in the fact that, since it's the DB that generates the ID, NHibernate needs a round trip to fetch it. 这个问题在于,由于它是生成ID的DB,因此NHibernate需要往返才能获取它。 As an example, for Server's identity fields the actual INSERT statement must be executed before SCOPE_IDENTITY() returns a valid key. 例如,对于服务器的标识字段,必须在SCOPE_IDENTITY()返回有效密钥之前执行实际的INSERT语句。 And the only way to perform this operation safely is by flushing the session. 并且安全地执行此操作的唯一方法是刷新会话。

As an alternative to guids and identity you can try the "increment" generator to see if it fits your needs: http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/mapping.html#mapping-declaration-id-generator 作为guids和identity的替代品,您可以尝试使用“增量”生成器来查看它是否符合您的需求: http//www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/mapping.html#mapping -declaration-ID发电机

You should be aware that this approach won't be feasible if you cluster your app, or you have some other process or application inserting into the same table. 您应该知道,如果您对应用程序进行集群,或者您将某些其他进程或应用程序插入到同一个表中,则此方法将不可行。

PS: for further reading try http://unhandled-exceptions.com/blog/index.php/2008/12/11/on-choosing-an-identity-type/ PS:如需进一步阅读,请尝试http://unhandled-exceptions.com/blog/index.php/2008/12/11/on-choosing-an-identity-type/

I found the issue, I was using an identity as the primary key. 我发现了这个问题,我使用了一个身份作为主键。 Changing it to guid worked. 将它改为guid工作。

Try wrapping the session.Save(User) in a transaction and set the FlushMode to Commit. 尝试在事务中包装session.Save(User)并将FlushMode设置为Commit。

\n

That should assure that no calls are made to the db. 这应该确保不会对数据库进行任何调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM