Nhibernate Flush工作提交没有

时间:2014-03-24 21:25:11

标签: nhibernate

很抱歉,如果我的问题没有太多细节,但我是nhibernate的新手,所以不知道怎么说。我想知道为什么在Web应用程序中调用会话刷新不会抛出错误但是Commit会。

我通常使用此代码:

session.SaveOrUpdate(item);
session.Flush();

但如果我调用session.Commit(),我会收到a different object with the same identifier value was already associated with the session错误

不提交和刷新工作相同吗?

2 个答案:

答案 0 :(得分:3)

您遇到的NonUniqueObjectException会出现在以下情况中:

  • 调用当前 ISession实例以获取id,例如.Get<TEntity>(id),并且它会引用此项目A
  • 调用相同的 ISession实例以保持(SaveOrUpdate项目B 并且
    • 这两个项目具有相同的键(itemA.ID == itemB.ID
    • 两者都是不同的引用(itemA != itemB

因此,如果发生这种情况,则会抛出NonUniqueObjectException (&#34;具有相同标识符的另一个对象...&#34;)

Flush()及其通过FlushMode的配置是分离持久层概念的实现。我们正在与session进行工作/交互,调用Read操作(主要是立即执行或从缓存中提供),调用Write操作 - 这些操作已排队。 已执行。 INSERT,UPDATE,DELETE被发布到数据库引擎中。

只有在调用Flush()时,会话才会执行&#34;同步&#34;对DB的更改。 (众多之一)的优点是NHibernate可以管理写语句的顺序。

9.6. Flush

发表声明的顺序:

  • 所有实体插入,使用ISession.Save()
  • 以相同的顺序保存相应的对象
  • 所有实体更新
  • 所有集合删除
  • 所有集合元素删除,更新和插入
  • 所有收集插入
  • 所有实体删除,使用ISession.Delete()
  • 以相同的顺序删除相应的对象

最后,这是枚举FlushMode的一个片段,它确实配置了Flush()来电:

/// <summary> Represents a flushing strategy.</summary>
/// <remarks>
/// The flush process synchronizes database state with session state by detecting state
/// changes and executing SQL statements
/// </remarks>
[Serializable]
public enum FlushMode
{
    /// <summary>
    /// Special value for unspecified flush mode (like <see langword="null" /> in Java).
    /// </summary>
    Unspecified = -1,
        /// <summary>
    /// The <c>ISession</c> is never flushed unless <c>Flush()</c> is explicitly
    /// called by the application. This mode is very efficient for read only
    /// transactions
    /// </summary>
    Never = 0,
        /// <summary>
    /// The <c>ISession</c> is flushed when <c>Transaction.Commit()</c> is called
    /// </summary>
    Commit = 5,
        /// <summary>
    /// The <c>ISession</c> is sometimes flushed before query execution in order to
    /// ensure that queries never return stale state. This is the default flush mode.
    /// </summary>
    Auto = 10,
        /// <summary>
    /// The <see cref="ISession"/> is flushed before every query. This is
    /// almost always unnecessary and inefficient.
    /// </summary>
    Always = 20
}

答案 1 :(得分:0)

似乎是因为我有FlushMode.Commit而不是FlushMode.Auto。不是100%肯定为什么

相关问题