开发者

Using NHibernate, how can I save all my repositories in a single Save()

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 repositorie开发者_开发技巧s. 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?


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();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜