NHibernate:如何选择具有单个孩子的父母(知道childID)?
我想将孩子添加到父母中。我什么时候知道孩子的新身份证?我可以在数据库插入之前访问它吗?我的 ID 生成器是 HILO。我问的原因是父对象的副本需要传播到另一个应用程序。知道这一点可能会节省我去数据库的次数,只是为了发现新插入的子项的 ID 是什么,因为我已经拥有了所有其他信息。
如果 1) 无法在没有往返数据库的情况下完成,那么(插入后)我如何选择仅包含子项的父项?父母可能有多个孩子,但我只对只有该孩子的父母感兴趣。这对我来说不太有效:
父 = session.QueryOver() 。列表() .Where(p => p.Children.Select(c => c.Id == ChildId).First()).First();
我想要的 SQL 等效项是:
select Parent.Id, Children.* From Parent
join Children on Parent.Id = Children.ParentId
where ChildId = 1540096
I want to add child to a parent. At which point is the new ID of a child known to me? Can I access it before DB insert? My ID generator is HILO. The reason I'm asking is that copy of the parent object needs to be propagated to another app. Knowing this would would potentially save me a trip to DB just to discover what the ID of newly inserted Child is as I have all the other info already available to me.
If 1) can not be accomplished w/out roundtrip to a DB then (after an insert) how can I select parent with child only? Parent may have multiple children but I'm only interested in a parent with that child only. This is not quite working for me:
parent = session.QueryOver()
.List()
.Where(p => p.Children.Select(c => c.Id == ChildId).First()).First();
SQL equivalent I want is:
select Parent.Id, Children.* From Parent
join Children on Parent.Id = Children.ParentId
where ChildId = 1540096
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
Session.Save(YourObject)
上,将为您的对象填充 ID。但是,这不会导致立即插入数据库。实际插入将在会话刷新时进行(Transaction.Commit 等)。除此之外,使用您当前的方法,您可能会传播一个可能无法映射到现有对象的 Id。例如,假设您在插入之前传播了一个 Id,然后您的插入由于某种原因失败了。如何处理这种不一致的状态?请留意此案例和类似案例。
我给您的建议是不要传播可能无效的状态。
On
Session.Save(YourObject)
the ID will populated for your object. However, this will not result in a immediate insert to the database. The actual insert will take place on session flush (Transaction.Commit, etc).That aside, with your current approach, you may propagate an Id that may not map to an existing object. For example, imagine you propagate an Id before the insert and then your insert fails for whatever reason. How are gonna deal with this inconsistent state? Beware of this case and similar ones.
My advice to you is to not propagate state that may be invalid.