gpt4 book ai didi

c# - 如何在另一个 session 中更新具有惰性属性(代理对象)的对象?

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:35 25 4
gpt4 key购买 nike

我试图在一个 session 中获取具有惰性属性的对象,并试图在另一个 session 中更新它。但它没有这样做有一个错误:SecUserProxy 没有持久化(实际类是 SecUser)

我正在使用 NHibernate 3.4。当我用谷歌搜索时,我才知道它是一个bug。已修复。

我也遇到了这个 post其中据说如果您的代理对象实现了 INhibernateProxy,您可以取消代理该对象与 NHibernate。由于 NHibernate 不再支持可插入代理工厂(如 CaSTLe、LinFu 等),它使用一个内部代理工厂,我假设内部可能是 INhibernateProxy

所以我在新 session 中做了以下操作,我想将我的对象更新为:

 object unprox_obj = Session
.GetSessionImplementation()
.PersistenceContext.Unproxy(secUserobj);

期待获得相同的对象,但具有真实类型,即 SecUser,以便它可以无错误地更新。但它仍然返回一个代理对象。

我无法理解发生了什么?

更新:我刚刚意识到“secUserobj”不是 INhibernateProxy。那么我怎样才能使它成为 INhibernateProxy 以便在另一个 session 中更新我的对象?

 if (secUserobj is INHibernateProxy)
{
unprox_obj = Session
.GetSessionImplementation()
.PersistenceContext.Unproxy(secUserobj);
}

最佳答案

分离的对象(在一个 session 中加载,并保留为引用)可以重新附加。我们可以使用 session.Merge()session.Lock()

9.4.2. Updating detached objects

Many applications need to retrieve an object in one transaction, send it to the UI layer for manipulation, then save the changes in a new transaction....

...

...The last case can be avoided by using Merge(Object o). This method copies the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. The method returns the persistent instance. If the given instance is unsaved or does not exist in the database, NHibernate will save it and return it as a newly persistent instance. Otherwise, the given instance does not become associated with the session. In most applications with detached objects, you need both methods, SaveOrUpdate() and Merge().

19.1.4. Initializing collections and proxies

...
You may also attach a previously loaded object to a new ISession with Merge() or Lock() before accessing uninitialized collections (or other proxies). No, NHibernate does not, and certainly should not do this automatically, since it would introduce ad hoc transaction semantics!
...

因此,我们可以将分离的引用传递给 .Merge(),然后使用返回的(全新) 对象引用:

MyEntity reAttached = session.Merge<MyEntity>(detached);

小心,这应该在任何分离的集合被触及之前完成(如上所述)。

关于c# - 如何在另一个 session 中更新具有惰性属性(代理对象)的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30371319/

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