NHibernate vs LINQ to SQL

LINQ to SQL forces you to use the table-per-class pattern. The benefits of using this pattern are that it’s quick and easy to implement and it takes very little effort to get your domain running based on an existing database structure. For simple applications, this is perfectly acceptable (and oftentimes even preferable), but for more complex applications devs will often suggest using a domain driven design pattern instead (which is what NHibernate facilitates).

The problem with the table-per-class pattern is that your database structure has a direct influence over your domain design. For instance, let’s say you have a Customers table with the following columns to hold a customer’s primary address information:

  • StreetAddress
  • City
  • State
  • Zip

Now, let’s say you want to add columns for the customer’s mailing address as well so you add in the following columns to the Customers table:

  • MailingStreetAddress
  • MailingCity
  • MailingState
  • MailingZip

Using LINQ to SQL, the Customer object in your domain would now have properties for each of these eight columns. But if you were following a domain driven design pattern, you would probably have created an Address class and had your Customer class hold two Address properties, one for the mailing address and one for their current address.

That’s a simple example, but it demonstrates how the table-per-class pattern can lead to a somewhat smelly domain. In the end, it’s up to you. Again, for simple apps that just need basic CRUD (create, read, update, delete) functionality, LINQ to SQL is ideal because of simplicity. But personally I like using NHibernate because it facilitates a cleaner domain.

Edit: @lomaxx – Yes, the example I used was simplistic and could have been optimized to work well with LINQ to SQL. I wanted to keep it as basic as possible to drive home the point. The point remains though that there are several scenarios where having your database structure determine your domain structure would be a bad idea, or at least lead to suboptimal OO design.

Leave a Comment