NHibernate and the dark secrets of unneeded cascaded updates

I was having trouble with NHibernate cascading an update to a related entity regardless of cascade=”none”. During my investigation I learned that when you pass an entity to ISession.Save, .Update or .SaveOrUpdate, NHibernate goes through the entire object graph and updates persisted entities if it thinks they’re “dirty” – as in a changed state compared to the cached one – regardless of your cascade setting. NHibernate has several ways to determine whether an object is dirty, the last resort one being comparing the values of each individual field of an entity.

Turns out, I had my mapping screwed up. My related entity Y had two enumeration fields that I’d mapped as Int32. This throws off the comparisons. Int32.Equals doesn’t consider an enum of value 0 equal to the Int32 value 0. So every time I saved an entity referring to Y it considered entity Y dirty and updated it. Solution: in your mapping file, define the type of the field as the actual enumeration type or just leave the type out and let NHibernate figure it out.

How to nest NHibernate mapping files in Visual Studio projects

Nesting files in Visual Studio projects is as simple as (pun intended) opening your project file into a text editor, finding your reference to a project file and adding <DependentUpon>Class.cs</DependentUpon> within the element.

However, there’s a catch. Nesting the files causes the file names to be overwritten. In this case, the .hbm.xml suffix gets dropped. That effectively prevents Configuration.AddAssembly() from finding the mapping information. A way around this pitfall is defining the dependency as follows:

<EmbeddedResource include="ServiceRequest.hbm.xml">
<DependentUpon>ServiceRequest.cs</DependentUpon>
<LogicalName>ServiceRequest.hbm.xml</LogicalName>
</EmbeddedResource>

Thanks go to Sami for cracking this nut with me.

C# and multiple inheritance

God damn I’m a crap blogger.

There. I’ve said it. And now onto the rant of the day. Why doesn’t C# support multiple inheritance? Well the official answer, as stated by Chris Brumme:

1. Different languages actually have different expectations for how MI works. For example, how conflicts are resolved and whether duplicate bases are merged or redundant. Before we can implement MI in the CLR, we have to do a survey of all the languages, figure out the common concepts, and decide how to express them in a language-neutral manner. We would also have to decide whether MI belongs in the CLS and what this would mean for languages that don’t want this concept (presumably VB.NET, for example). Of course, that’s the business we are in as a common language runtime, but we haven’t got around to doing it for MI yet.

2. The number of places where MI is truly appropriate is actually quite small. In many cases, multiple interface inheritance can get the job done instead. In other cases, you may be able to use encapsulation and delegation. If we were to add a slightly different construct, like mixins, would that actually be more powerful?

3. Multiple implementation inheritance injects a lot of complexity into the implementation. This complexity impacts casting, layout, dispatch, field access, serialization, identity comparisons, verifiability, reflection, generics, and probably lots of other places.

Yea. Well. All of these are probably valid and good reasons why there is no multiple inheritance in C#. However, I just stumbled upon a frustrating scenario today where the lack of MI is a pain.

The architecture I’m developing at the moment is using NHibernate for data access and I’d like to implement a data model, in which the database has e.g. the tables Person, UserAccount, Employee and Company. In the domain model I’d like to have classes for each of those tables, so that you could deal with companies and users as such, but also have classes like CompanyUser, that inherits from UserAccount and Company both. The former is of course in this particular case, where UserAccount and Company have a one-to-one relationship (well technically speaking it’s a many-to-one, but logically a one-to-one), which is a typical scenario in some of the software we have under construction. In the case of an employee, the employee table just extends the data of a person record so single inheritance works just fine there.

Having said that, I already see some problem materializing with multiple inheritance. All of my domain model classes inherit from a base class that includes some time stamp fields common to all entities. Imagining a case, where you first create a company and at a later point in time create a corresponding user account, you’d end up with differing timestamps for the company and user account. Now, having the CompanyUser class inherit from both results in a conflict.

Which base class’s timestamps should be inherited? A solution I could think of, would be to – in case of MI – inherit both but give them a syntactically different exposure. E.g. if I had a CompanyUser object cu, I could refer to the base Company’s UpdatedOn property like cu.base[Person].UpdatedOn or something similiar.

I hear what you’re saying. Why don’t I just extract interfaces from from Company, UserAccount etc?

Firstly, interfaces are already running amok in a loosely coupled architecture such as mine, and I really don’t feel the idea of calling everything thru interfaces. It just makes navigating in the code that much harder. So referring to something within the same assembly and even the same namespace, with no actual possibility to ever change the implementation of a entity class such as the UserAccount, thru an interface just makes no sense to me. The implementation is there and it’s always the same so no reason to mess with middle hands here.

Secondly, in addition to the obfuscating effect of interfaces in this scenario, it adds stupid amounts of work. Consider this:

  1. Create the tables Company and UserAccount
  2. Generate the entity classes and mapping files for both with MyGeneration
  3. Extract interfaces of both the classes
  4. Create a new class CompanyUser that implements the interfaces
  5. Copy+paste pretty much the whole classes to the “inheriting class” to achieve proper implementation (private members, internal accessors for NHibernate and the public accessors)
  6. Create a mapping file for the “inheriting class”
  7. The data schema changes -> repeat from 2

Thirdly, wouldn’t it be nice to ask NHibernate for a UserAccount and receive a CompanyUser or PersonUser or whatever, that you could later on cast to either of those types if needed?

At the moment I have a class CompanyUser, that inherits the class UserAccount and implements the interface ICompany. It has a Company field that is exposed via the ICompany properties. I guess this works for now, but In case of a schema change it’s proven a bit cumbersome.