Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何保存NHibernate会话中已经存在的临时对象?_C#_Nhibernate_Persistence_Session State_Castle Activerecord - Fatal编程技术网

C# 如何保存NHibernate会话中已经存在的临时对象?

C# 如何保存NHibernate会话中已经存在的临时对象?,c#,nhibernate,persistence,session-state,castle-activerecord,C#,Nhibernate,Persistence,Session State,Castle Activerecord,我有一个商店,里面有产品的列表: var store = new Store(); store.Products.Add(new Product{ Id = 1, Name = "Apples" }; store.Products.Add(new Product{ Id = 2, Name = "Oranges" }; Database.Save(store); 现在,我想编辑一个产品,但要使用一个临时实体。例如,这将是来自web浏览器的数据: // this is what I get f

我有一个
商店
,里面有
产品的列表

var store = new Store();
store.Products.Add(new Product{ Id = 1, Name = "Apples" };
store.Products.Add(new Product{ Id = 2, Name = "Oranges" };

Database.Save(store);
现在,我想编辑一个
产品
,但要使用一个临时实体。例如,这将是来自web浏览器的数据:

// this is what I get from the web browser, this product should
// edit the one that's already in the database that has the same Id
var product = new Product{ Id = 2, Name = "Mandarin Oranges" };

store.Products.Add(product);
Database.Save(store);
但是,尝试这样做会给我一个错误:

具有相同标识符值的不同对象已与会话关联


原因是
store.Products
集合中已包含具有相同Id的实体。如何解决此问题?

也许您应该调用Database.SaveOrUpdate(store);在这种情况下,如果没有更多的上下文,我不是100%肯定,而是完全保存(存储)?

但是会话合并可能会起作用


而不是尝试合并临时实例。为什么不从实际实例开始…只需通过id获取产品,更新字段,然后提交

var product = session.Get<Product>(2);
product.Name = "Mandarin Oranges";
tx.Commit();

在第二次保存之前,您是否尝试过session.execute(产品)?哎呀,忘了提到
数据库。Save()
在幕后执行
NHibernate.ISession.SaveOrUpdate()
。SaveOrUpdate在这种情况下没有帮助,因为会话中已经有对象,所以会发生错误。感谢链接,很好地解释了为什么会出现这个问题。
var product = new Product{ Id = 2, Name = "Mandarin Oranges" };
var mergedProduct = (Product) session.Merge(product);
tx.Commit();