我有一个包含产品列表的商店:
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);
但是,尝试这样做会给我一个错误:
a different object with the same identifier value was already associated with the session
原因是因为store.Products集合已经包含具有相同Id的实体.我该如何解决这个问题?
解决方法
而不是尝试合并瞬态实例.为什么不从实际实例开始…只需通过id获取产品,更新字段并提交.
var product = session.Get<Product>(2); product.Name = "Mandarin Oranges"; tx.Commit();
或合并方式……
var product = new Product{ Id = 2,Name = "Mandarin Oranges" }; var mergedProduct = (Product) session.Merge(product); tx.Commit();