如何保存NHibernate会话中已存在的瞬态对象?

Dan*_* T. 6 c# nhibernate persistence castle-activerecord session-state

我有一个Store包含以下列表的列表Products:

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);
Run Code Online (Sandbox Code Playgroud)

现在,我想编辑其中一个Products,但是有一个瞬态实体.例如,这将是来自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);
Run Code Online (Sandbox Code Playgroud)

但是,尝试这样做会给我一个错误:

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

原因是因为store.Products集合已包含具有相同Id的实体.我该如何解决这个问题?

dot*_*joe 8

而不是尝试合并瞬态实例.为什么不从实际实例开始...只需通过id获取产品,更新字段并提交.

var product = session.Get<Product>(2);
product.Name = "Mandarin Oranges";
tx.Commit();
Run Code Online (Sandbox Code Playgroud)

或合并方式......

var product = new Product{ Id = 2, Name = "Mandarin Oranges" };
var mergedProduct = (Product) session.Merge(product);
tx.Commit();
Run Code Online (Sandbox Code Playgroud)