使用 NHibernate,如何在单个 Save() 中保存所有存储库

发布于 2024-10-25 18:10:27 字数 477 浏览 3 评论 0原文

我在使用 NHibernate 的项目中使用存储库/工作单元模式。我有许多存储库,例如客户和帐户。通过将相同的 ISession 对象传递给每个存储库的构造函数,每个存储库都与相同的 ISession(工作单元模式)相关联。

然后,我创建一堆客户及其关联帐户,并将它们添加到各自的存储库中。现在我想将这些存储库保存到数据库中。然而,在 NHibernate 中保存需要调用 ISession.Save() 并传入一个实体。如果我使用实体框架,并且我的 ISession 是一个 ObjectContext,我将能够调用 ObjectContext.SaveChanges() 并且所有存储库的内容都将保存到数据库中。

我怎样才能在 NHibernate 中做到这一点?我必须单独保存每个对象,而不是整个 ISession,这似乎很奇怪。我还必须按特定顺序保存它们,因为客户必须有一个帐户(客户表中的 AccountID FK 不能为空),因此我必须首先保存帐户,然后保存客户。

我错过了什么?

I'm using the Repository/Unit of Work pattern in a project using NHibernate. I have a number of repositories, such as Customer and Account. Each repository is associated with the same ISession (unit of work pattern) by passing in the same ISession object to the constructor of each repository.

I then create a bunch of customers and their associated accounts and add them to their respective repositories. Now I want to save these repositories to the database. However, to save in NHibernate involves calling ISession.Save() and passing in an entity. If I was using the Entity Framework instead, and my ISession was an ObjectContext, I would be able to call ObjectContext.SaveChanges() and the contents of all my repositories would be saved to the database.

How can I do this in NHibernate? It seems odd that I have to save each object individually, rather than the ISession as a whole. I also have to save them in a specific order, since a Customer must have an account (AccountID FK in customer table cannot be null) I must therefore save the account first, followed by the customer.

What have I missed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧情勿念 2024-11-01 18:10:27

您不需要显式保存对象。 Hibernate 的构建考虑到了所谓的“持久性无知”。只需刷新会话,对所有已知实体的所有更改都将被保留。

所以只需调用 Session.Flush();

You don't need to save your objects explicitly. Hibernate has been built with so called "Persistence Ignorance" in mind. Just flush the session and all changes to all known entitys will be persisted.

So just call Session.Flush();

‖放下 2024-11-01 18:10:27

您错过了将新对象与 ISession 关联的部分 (session.Save())。否则 NH 如何知道您创建的某个对象需要持久化?如果您只修改现有对象(从 ISession 获取的对象),那么您所需要做的就是提交事务/刷新会话。

对于客户->帐户关系,您可以使客户级联保存在其帐户上。

You missed the part where you associate a new object with the ISession (session.Save()). Otherwise how does NH know that some object you created needs to be persisted? If you are only modify existing objects (that you've fetched from the ISession) then all you need to do is commit the transaction/flush the session.

For the customer -> account relationship, you could make the customer cascade saves on it's account.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文