Tag: NHibernate

Fluent NHibernate – mapping one to one relation

Posted by – March 7, 2012

Few weeks ago I’ve started new project based on ASP.NET MVC, jQuery and NHibernate. It has some part of functionality inspired by ELMAH but mainly goes in a different direction addressing some additional scenarios and it is called WebConsole. It is able to catch exceptions from ASP.NET application and save them with whole context in centralized database. It can also log every request and response even if there was no exception. As you can see everything is spinning around HTTP request and response model.

In order to store information about HTTP communication I had to create NHibernate entities and map them to a database. After some short brainstorming I came up with three basic entities:

Activity – representing single “act” of communication between a client and a server

public class Activity : Entity
{
    // ... some properties and methods removed for readability

    public virtual int Id { get; set; }

    private Request _request;
    public virtual Request Request
    {
        get { return _request; }
    }

    public virtual void Add(Request request)
    {
        if (_request != null)
        {
            _request.Activity = null;
        }
        _request = request;
        _request.Activity = this;
    }

    private Response _response;
    public virtual Response Response
    {
        get { return _response; }
    }

    public virtual void Add(Response response)
    {
        if (_response != null)
        {
            _response.Activity = null;
        }
        _response = response;
        _response.Activity = this;
    }
}

Request – representing request made by the client

public class Request : Entity
{
    // ... some properties  and methods removed for readability

    public virtual int Id { get; set; }

    public virtual Activity Activity { get; set; }
}

Response – representing response from the server

public class Response : Entity
{
    // ... some properties  and methods removed for readability

    public virtual int Id { get; set; }

    public virtual Activity Activity { get; set; }
}

During one Activity there can be no more than one Request and Response. With this assumptions in mind I’ve started thinking how to map these relations using Fluent NHibernate. It was obvious for me that this are one to one relations, but turned out it is not so obvious how to map them. After some googling, playing with the code and a cup coffee I found right configuration which work nice.

From the Activity side relations has been mapped in a standard way by using HasOne method with some other modifiers for the access and lazy loading. One thing worth mention is Id mapping with automatically generated values.

public sealed class ActivityMap : ClassMap
{
    public ActivityMap()
    {
        // ... some mappings removed for readability

        Id(x => x.Id);

        HasOne(x => x.Request).Access.CamelCaseField(Prefix.Underscore)
                .Cascade.All().LazyLoad();

        HasOne(x => x.Response).Access.CamelCaseField(Prefix.Underscore)
                .Cascade.All().LazyLoad();
    }
}

From the Request and the Response mapping side thing looks quite different. This is because I had to “tell” that Id should not be automatically generated but taken from the Activity. Additionally HasOne relation looks different because it has to act as a foreign key and be constrained to values of the Activitie’s identifier (Id).

public sealed class RequestMap : ClassMap
{
    public RequestMap()
    {
        // ... some mappings removed for readability

        Id(x => x.Id).GeneratedBy.Foreign("Activity");

        HasOne(x => x.Activity).Constrained().ForeignKey();
    }
}

public sealed class ResponseMap : ClassMap
{
    public ResponseMap()
    {
        // ... some mappings removed for readability

        Id(x => x.Id).GeneratedBy.Foreign("Activity");

        HasOne(x => x.Activity).Constrained().ForeignKey();
    }
}

At the end we came up with a solution where the main entity is responsible for generating identifiers and all other entities in one to one relation use them as theirs primary and foreign keys.

Fluent NHibernate conventions II – example for enumerations

Posted by – May 20, 2010

Most of the time I do not have to touch Fluent NHibernate conventions I have created some time ago. But from time to time I find in mappings some common scenario which is a good candidate to become a convention. This time I found that every time I am mapping a property of enumeration type I have to specify its length manually.

Because I hate redundant work I have defined a Fluent NHibernate convention presented below.

using System;
using System.Linq;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.AcceptanceCriteria;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.Conventions.Instances;

namespace ExampleConventions
{
    public class EnumColumnLengthConvention
        : IPropertyConvention, IPropertyConventionAcceptance
    {
        public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
        {
            criteria.Expect(x => x.Property.PropertyType.IsEnum)
                .Expect(x => x.Length == 0);
        }

        public void Apply(IPropertyInstance instance)
        {
            var names = Enum.GetNames(instance.Property.PropertyType);
            instance.Length(names.Max(name => name.Length));
        }
    }
}

The convention is really simple. Its whole logic can be found in Apply method and I think it is self explanatory so there is nothing to describe here.

Fluent NHibernate conventions – examples

Posted by – November 26, 2009

Fluent NHibernateFluent NHibernate is my favorite extension for NHibernate. I am using it since early betas and I have to say that I love it. One of its underestimated features are conventions. I decided to extract some of them from one of my projects and provide real life examples how they can be used. My conventions are listed below but if you need more information visit Fluent NHibernate Wiki where this feature is described in detail.

ColumnNullabilityConvention – says that if nullability for column has not been specified explicitly, should be set to “NOT NULL”.

public class ColumnNullabilityConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Nullable, Is.Not.Set);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Not.Nullable();
    }
}

CreatedAtPropertyAccessConvention – says that every property named CreatedAt should be accessed through camel case field hidden behind it.

public class CreatedAtPropertyAccessConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.Name == "CreatedAt");
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Access.ReadOnlyPropertyThroughCamelCaseField(
            CamelCasePrefix.Underscore);
    }
}

ForeignKeyConstraintNameConvention – says that name of every foreign key constraint representing one to many relation should consist of names of entities for which it was specified.

public class ForeignKeyConstraintNameConvention
    : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance instance)
    {
        instance.Key.ForeignKey("{0}_{1}_FK".AsFormat(
        instance.Member.Name, instance.EntityType.Name));
    }
}

ForeignKeyNameConvention – says that name of every column containing foreign key id should consist of name of type which it points to with “Id” suffix.

public class ForeignKeyNameConvention : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance instance)
    {
        instance.Key.Column(instance.EntityType.Name + "Id");
    }
}

PrimaryKeyNameConvention - says that name of every column representing primary key should consist of entity name and “Id” suffix.

public class PrimaryKeyNameConvention : IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {
        instance.Column(instance.EntityType.Name + "Id");
    }
}

ReferenceConvention – says that name of column referenced in many to one convention should consist of entity name and “Id” suffix.

public class ReferenceConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        instance.Column(instance.Property.PropertyType.Name + "Id");
    }
}

StringColumnLengthConvention – says that if length for string column has not been specified, it should be set to 100.

public class StringColumnLengthConvention
    : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Type == typeof(string))
            .Expect(x => x.Length == 0);
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Length(100);
    }
}

TableNameConvention – says that if name for table has not been specified, it should be created using concatenation of entity name and “s” suffix.

public class TableNameConvention
    : IClassConvention, IClassConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IClassInspector> criteria)
    {
        criteria.Expect(x => x.TableName, Is.Not.Set);
    }

    public void Apply(IClassInstance instance)
    {
        instance.Table(instance.EntityType.Name + "s");
    }
}

At the end the most important thing which shows that such conventions make sense. With default Fluent NHibernate conventions DDL generated by NHibernate for MySQL looked like this:

alter table `Athlete`  drop foreign key FK9221C9B94070A6F0

drop table if exists Countries

drop table if exists `Athlete`

create table Countries (
     Id INTEGER NOT NULL AUTO_INCREMENT,
     Name VARCHAR(255),
     primary key (Id)
)

create table `Athlete` (
     Id INTEGER NOT NULL AUTO_INCREMENT,
     DisplayName VARCHAR(255),
     Email VARCHAR(255),
     Password VARCHAR(255),
     CreatedAt DATETIME,
     IsActive TINYINT(1),
     Country_id INTEGER,
     primary key (Id)
)

alter table `Athlete`
	add index (Country_id),
	add constraint FK9221C9B94070A6F0
	foreign key (Country_id)
	references Countries (Id)

When I have applied conventions mentioned above to my fluent mappings DDL looks like this:

alter table Athletes  drop foreign key Athletes_Country_FK

drop table if exists Athletes

drop table if exists Countries

create table Athletes (
     AthleteId INTEGER NOT NULL AUTO_INCREMENT,
     DisplayName VARCHAR(100) not null,
     Email VARCHAR(100) not null,
     Password VARCHAR(100) not null,
     CreatedAt DATETIME not null,
     IsActive TINYINT(1) not null,
     CountryId INTEGER,
     primary key (AthleteId)
)

create table Countries (
     CountryId INTEGER NOT NULL AUTO_INCREMENT,
     Name VARCHAR(100) not null,
     primary key (CountryId)
)

alter table Athletes
	add index (CountryId),
	add constraint Athletes_Country_FK
	foreign key (CountryId)
	references Countries (CountryId)

For me it looks much better. Additionally I have made it once and that is it. Now I have to care only about domain model and business logic without thinking about not so important stuff lake names of database objects.