NHibernate;保存到数据库时更新分离集合中实体的 Id 属性
我使用每次调用会话来保存一个分离的集合以及可能的添加/更新(因此包括一些瞬态对象)。但是如何更新新实例的Id(暂时的),它是0,但现在(保存到数据库后)应该有一个值?
我是说;正确更新数据库后,更新传递的集合的这些 Id。
您会在存储库中执行此操作吗?如果是这样,怎么办? ..如果没有,还能怎样?
考虑一下它是可能也有新实例的级联子集合,那么它会变得有点复杂。希望对此有一些想法/建议。
class StoreRepository
{
public static void SaveOrUpdate(List<Store> stores)
{
using (ISession session = FNH_Manager.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
foreach (var s in stores)
{
session.Get(typeof(Store), s.Id);
session.SaveOrUpdateCopy(s);
}
transaction.Commit();
}
}
}
I use session-per-call to save a detached collection with possible adds/updates (so includes some transient objects). But how to update the Id's of new instances(transient), which was 0, but now (after saving to database) should have a value?
I mean; Update those Id's of the passed collection, after the database is updated properly.
Would you do this in the repository? If so, how? ..and if not, how else?
What about considering it's cascading child collections that may also have new instances, then it gets a bit complex. Would appreciate some thoughts/advice on this.
class StoreRepository
{
public static void SaveOrUpdate(List<Store> stores)
{
using (ISession session = FNH_Manager.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
foreach (var s in stores)
{
session.Get(typeof(Store), s.Id);
session.SaveOrUpdateCopy(s);
}
transaction.Commit();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确定持久对象没有更改,您可以使用
Lock
方法将其重新附加到新会话并进行修改。 Id=0 的新对象只是SaveOrUpdate
。If you are sure that persistent object was not changed you can re-attach it to new session with
Lock
method and make modifications. New objects which Id=0 justSaveOrUpdate
.未设置瞬态实例的 ID,似乎是由于使用 SaveOrUpdateCopy 所致。正如我在这里评论的那样。 NHibernate:身份ID如何保存瞬态实例时更新?
The Id's of transient instances not being set, seems to be due to using SaveOrUpdateCopy. As I commented here. NHibernate: How is identity Id updated when saving a transient instance?