很抱歉,如果我的问题没有太多细节,但我是nhibernate的新手,所以不知道怎么说。我想知道为什么在Web应用程序中调用会话刷新不会抛出错误但是Commit会。
我通常使用此代码:
session.SaveOrUpdate(item);
session.Flush();
但如果我调用session.Commit(),我会收到a different object with the same identifier value was already associated with the session
错误
不提交和刷新工作相同吗?
答案 0 :(得分:3)
您遇到的NonUniqueObjectException
会出现在以下情况中:
.Get<TEntity>(id)
,并且它会引用此项目A SaveOrUpdate
)项目B 并且
itemA.ID == itemB.ID
)itemA != itemB
)因此,如果发生这种情况,则会抛出NonUniqueObjectException
(&#34;具有相同标识符的另一个对象...&#34;)。
Flush()
及其通过FlushMode
的配置是分离持久层概念的实现。我们正在与session
进行工作/交互,调用Read
操作(主要是立即执行或从缓存中提供),调用Write
操作 - 这些操作已排队。 不已执行。 否 INSERT,UPDATE,DELETE被发布到数据库引擎中。
只有在调用Flush()
时,会话才会执行&#34;同步&#34;对DB的更改。 (众多之一)的优点是NHibernate可以管理写语句的顺序。 见
发表声明的顺序:
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%肯定为什么