[英]NHibernate How to update Id on IEntity
I have a row in my DB w/ Id = '00000000-0000-0000-0000-000000000000', 我的数据库中有一行w / Id ='00000000-0000-0000-0000-000000-000000000000',
how can I force update this Id using session/transaction ,basically assign a valid Id to the row. 我该如何使用会话/交易强制更新此ID,基本上将有效ID分配给该行。
I've tried: 我试过了:
var testrow = repo.get(id);
testrow.Id = Guid.NewGuid();
repo.UpdateRow(testRow);
My update repository update method: 我的更新存储库更新方法:
public void UpdateRow(TestRow row)
{
using (ISession session = _sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Update(row);
transaction.Commit();
}
}
I get the error: 我得到错误:
"Row was updated or deleted by another transaction"
If I attempt to delete the object using : 如果我尝试使用删除对象:
session.delete(row)
transaction.Commit();
I get the following error: 我收到以下错误:
Unexpected row count: 3; expected: 1
There are 3 rows each with a unique Id, one happens to have an incorrect Id of 00000000-0000-0000-0000-000000000000' 有3行,每行都有唯一的ID,其中一个恰好具有错误的ID 00000000-0000-0000-0000-000000000000'
An id must never change, this an error in your application design. id绝不能更改,这是您的应用程序设计中的错误。 Delete the old entity and recreate with the new values. 删除旧实体,然后使用新值重新创建。
I think you have not 1 row with that id - but three. 我认为您没有该ID的1行-而是3行。 Try using a DB-tool and do a regular select * from [table] where id = '00000000-0000-0000-0000-000000000000'
- I'll bet that is your problem. 尝试使用数据库工具,并select * from [table] where id = '00000000-0000-0000-0000-000000000000'
进行常规select * from [table] where id = '00000000-0000-0000-0000-000000000000'
我敢打赌,这就是您的问题。 That would give the unexpected error - and for the love of all that is good - have a unique constraint on you id-column :-). 这会带来意想不到的错误-并且出于对所有优点的热爱-对id列有唯一的约束:-)。
Also, your update method violates the unit of work pattern that is ISession. 另外,您的更新方法违反了工作单元模式ISession。 You load the object in one session, update it - and then try to make the update in another session - that is bound to give you unexpected results! 您在一个会话中加载对象,对其进行更新-然后尝试在另一个会话中进行更新-这势必会给您带来意想不到的结果!
Always make this kind of work in one ISession! 始终在一个 ISession中完成这种工作!
EDIT: By the way - nHibernate cannot update your Id - that is how nHibernate knows which object you are holding! 编辑:顺便说一句-nHibernate无法更新您的ID-这就是nHibernate如何知道您持有的对象! It simply doesn't make sense what you are doing. 这根本没有意义,你在做什么。 If you really need to update that row - use a DB-tool and do it manually (and take measures so it cannot happen again...) 如果您确实需要更新该行,请使用数据库工具并手动进行(并采取措施以防止再次发生...)
EDIT2: To correct the problem, use this in code: nHibernate supports raw sql - use ISession.CreateSQLQuery("DELETE FROM [table] WHERE Id = '00000000-0000-0000-0000-000000000000'").ExecuteUpdate(); EDIT2:若要更正此问题,请在代码中使用此代码:nHibernate支持原始sql-使用ISession.CreateSQLQuery(“从[表]删除,其中ID ='00000000-0000-0000-0000-000000000000'”)。ExecuteUpdate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.