Sunday, January 18, 2009

Layered Architecture with LINQ to SQL (Part 1)

As with many other Microsoft technologies LINQ to SQL mainly supports a RAD (rapid application development) style of development. You can drag and drop tables into the LINQ to SQL Designer and Visual Studio will define a simple 1:1 mapping, generate domain classes and a typed datacontext for your database. All set, ready to hack! Let's create a win form, drag some controls in it, code some LINQ to SQL queries in a click event handler and bind it to a grid. Sounds easy right? Well it's easy and you can do it, but consider the following problems:
  • Writing database queries in your presentation layer is not as bad as using SQL code in it, but it’s still a questionable practice. If you do it, you’re mixing data access code with business logic and presentation code. This means that you’ve decided to abandon the benefits of the separation of concerns.
  • LINQ to SQL queries are scattered around in your business logic or presentation code. Sooner or later you run into a maintenance problem.
  • There is no concept for code reuse. Queries that need to be used at different places have to be duplicated.
But that doesn't mean that LINQ to SQL is not suitable for building layered enterprise applications. There are a lot of resources available that can help you to structure your data access logic. Most of them are documented in Martin Fowler's Patterns of Enterprise Application Architecture (PEAA) book. If you choose the Domain Model approach there are mainly two options for your DAL:
  • Active Record. Active Record puts data access logic directly in the domain object. In most implementations you can see a set of static finder methods on the domain objects and instance methods for operations like save, update and delete.
  • Pure Domain Model with a Unit Of Work and Repositories. This approach separates the data access logic from the domain objects. With the combination of these patterns different objects exist for different concerns: the unit of work is responsible for change tracking, repositories for data access and domain object for domain logic.
In my next post I want to show you how I would apply the pure Domain Model patterns in the context of LINQ to SQL.

No comments: