gpt4 book ai didi

c# - 使用 DefaultCascade.All() 将实体添加到列表时,Nhibernate 不设置 Id

转载 作者:行者123 更新时间:2023-11-30 21:13:11 24 4
gpt4 key购买 nike

使用 ASP.net MVC 我这样做:

[HttpPost]
[TransactionFilter]
public ActionResult Create(User user)
{
// Ommited some things for the sake of brevity
_userRepository.Add(user);
return RedirectToAction("Details", new { Id = user.Id });
}

这如我所料。现在我正在尝试这样做:

[HttpPost]
[TransactionFilter]
public ActionResult Create(User user, ChildOfUser userChild)
{
// Ommited some things for the sake of brevity
var parent = _userRepository.GetById(user.Id);
parent.Children.Add(userChild);

return RedirectToAction("Details", new { Id = userChild.Id });
}

这失败了,因为 userChild.Id 为空。第一种情况有效,因为在 repo 中我调用了 session.Save(user);,这个调用将更改 user.Id 属性。

(User)parent.Children.Add(userChild); 调用不会更改 userChild.Id 属性。只有在调用 transaction.Commit(); 之后,userChild.Id 才会具有有意义的值。虽然我希望通过将 userChild 添加到集合中来设置 Id。

现在,NHibernate 应该处理这个吗?还是我的期望错了?如果有办法让 NHibernate 处理这个问题,那就太棒了。

编辑在这种情况下,Id 始终是 GUID。我可以自己设置它们吗(它们全局是唯一的...),NHibernate 会像它自己生成 Id 一样使用它吗?

最佳答案

parent.Children.Add(userChild); 与 NHibernate 无关,它们是内存操作,实际上它们是 .NET 基础库的一部分,很久以前就有人移植了休眠到 .NET。 collection.Add 不是 NHibernate 操作

Only after calling transaction.Commit(); the userChild.Id will have a meaningfull value. While I expect that the Id would be set by adding the userChild to the collection.

您观察到的是正确的,只有当您调用保存/提交时,NHibernate 对您的对象的作用才会发挥作用。

关于c# - 使用 DefaultCascade.All() 将实体添加到列表时,Nhibernate 不设置 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6972942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com