[英]Using CreateSQLQuery with INSERT query in NHibernate
What is the state of the object, if it is added with using INSERT query? 如果使用INSERT查询添加了对象,则该对象的状态是什么? And how i can get this object same session? 而我如何才能使该对象相同的会话?
Insert Object using native SQL 使用本机SQL插入对象
session.CreateSQLQuery("INSERT INTO table (...) VALUES (...)").ExecuteUpdate())
I know his Id, so using this for get: 我知道他的ID,因此可以使用此代码获取:
sessison.Get<MyObjectType>(id)
but object is null, because the session is same and commit is still pending. 但object为null,因为会话相同,并且提交仍处于待处理状态。 What am I doing wrong? 我究竟做错了什么?
PS Using CreateSQLQuery need, because my child object foo created based on his parent bar, but bar and foo have same Id, and used Table Per Concrete Class PS需要使用CreateSQLQuery,因为我的子对象foo基于其父级bar创建,但是bar和foo具有相同的ID,并使用Table Per Concrete Class
Either commit the first transaction before attempting the .Get
or you might be able to use .Load
instead if you only need to associate this entity with another entity before an update or insert. 尝试执行.Get
之前先提交第一个事务,或者如果只需要在更新或插入之前将此实体与另一个实体关联,则可以使用.Load
代替。
Writing raw sql queries will not save things in session as you are not dealing with entities. 编写原始sql查询不会将内容保存在会话中,因为您不处理实体。
I found solution. 我找到了解决方案。
In my case, ISessionProvider
have Life style - perWebRequest
. 就我而言, ISessionProvider
具有生活方式perWebRequest
。 This means that session be commited after the end web request. 这意味着会话将在结束Web请求之后提交。
Next. 下一个。 After insert, we have no entity, but we can merge new entity, created based on data for insert, with current session. 插入后,我们没有实体,但是可以将基于插入数据创建的新实体与当前会话合并。
session.Merge(new Entity(...));
or if you have parent entity in Persistence Context
, you need do so: 或者,如果您在Persistence Context
具有父实体,则需要这样做:
session.Evict(parentEntity);
session.Merge(new Entity(...));
Evict
remove entity with some id (child and parent have some id), else you will get an exception. Evict
一些id取消实体(小孩和父母有一定的ID),否则你会得到一个异常。 This will merge entity with current session, and when you use sessison.Get<MyObjectType>(entityId)
object doesn't be null. 这将与当前会话合并实体,并且当您使用sessison.Get<MyObjectType>(entityId)
对象不为null时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.