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

标签 c# nhibernate domain-driven-design

使用 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 为 null。第一种情况有效,因为在存储库中我调用 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 基础库的一部分,很久以前就有人将 Hibernate 移植到 .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.

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

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

相关文章:

model - 域逻辑泄漏到其他层?

c# - DDD : what are the OOP alternatives for procedural Application Services?

asp.net - NHibernate 的 log4net 未将任何内容写入 ASP.NET 跟踪

domain-driven-design - 所有的类都包含业务逻辑、域对象吗?

c# - Emgu Opencv C# ConvertTo 不同的结果

c# - C#在运行时更改进程FileName

c# - nhibernate在Mysql中如何存储TimeSpan?

nhibernate - 如何在 Fluent NHibernate 中关闭锁定?

c# - 无论行号如何,如何保持 Gridview 的高度相同?

C# WPF SizeChanged 事件在最大化时不更新宽度和高度