- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 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/
使用 ASP.net MVC 我这样做: [HttpPost] [TransactionFilter] public ActionResult Create(User user) { // O
我是一名优秀的程序员,十分优秀!