NHibernate Best Practice - Assert Cascade Behaviors
I've said it before, one of the trickiest parts on NHibernate is the cascade behaviors. Why is it tricky? Because a slight configuration can cause the application to get exception at best, or silently lose data at worst.
How does this work? Let us assume that I have the Blog -> Posts model, and I want to create a new post. I can do this like this:
using(ISession session = factory.OpenSession())
{
Blog blog = session.Load(typeof (Blog), 1) as Blog;
blog.Posts.Add(new Post("NHibernate", "Best", "Practices"));
session.Flush();
}
Because the way I defined the cascades from blog to posts, this will save the new post to the database. But there are a lot of reasons to change the cascading options. The problem that such a change can break the implicit assumption in the code above. Depending on the specific setting that was set, it may throw an exception or silently ignore the new value.
Because of this, I usually document my assumptions using tests. I got tests like:
- SavingABlogSavesAllItsPosts
- SavingAPostDoesNotSaveComments
After having to go through the pain of changing the configuration and ending up bad results, I make sure that if I break one of the assumption that I did, I'll at least be aware of it. There is a good chance that I will decide to go ahead with the change anyway, but this will make sure that I will double check the assumptions that the rest of the code does, and not blithely continue on the way to unpleasantness.
Comments
Comment preview