Monday, November 29, 2010

Linq to NHibernate: no data layer!

NHibernate 3 includes Linq. These two combined makes your datalayer 'dissapear'. In the following example I'll show you how to set up your entities in a way you can reference them from your code without any knowledge of the underlying database and database model.
I will give this example with the widely known Northwind database.

On the right a picture shows an outline of the project. NortwindEntities is a .NET 3.5 Class library with references to NHibernate 3.

There are two folders: one containing the entities (objects), and one containing the mapping files used by NHibernate to map the entities-logic to the relational database. The final file is called NortwindContext.cs. This file contains functionality to setup a SessionFactory and a Session. The depended file (actually a partial class) NortwindContext.Entities.cs holds properties to access the entities of the context in a proper way. For example in Linq to NHibernate the Customer entity is referenced as:


The NorthwindContext has a property Customers:

public IQueryable<Customers> Customers
get { return Session.Query<Customers>(); }

Setting up this Class library is the difficult part. But when it is done, you can reference it from your application. With two lines of code you have set up the Context (including the connection to the database)

// Set up the servername once
// Create a new context
var nc = new NorthwindContext(true);

Retrieving your entities is as simple as:

var customers = nc.Customers.Select(c =>
new { c.ContactName, c.Orders.Count });

Saving your entities isn't that hard anymore:

var customer = new Customer
Id = "FOE",
ContactName = "Frank",
City = "Dalem"

Conclusion: The datalayer kind of dissapeared.

You can download the example solution here. It also includes the SQL-script to generate the Northwind database in your SQL Server (express) enviroment.

1 comment:

Rob said...

Really great post! Got this working within minutes inside SharePoint! Thanks a lot!