Self Referencing Table Joins in FluentNHibernate

A common usage of the self-referencing joins is the use of 1 table for regions and subregions; its also the laziest example that comes to mind.

Entity

using System.Collections.Generic;  
using Domain.Base;

public class Region : DomainObject<int, Region>  
{
    private IList<Region> _subRegion = new List<Region>();
    public virtual string Name { get; set; }

    public virtual IList<Region> SubRegion
    {
        get { return _subRegion; }
        set { _subRegion = value; }
    }
}

ClassMap

using Domain;  
using FluentNHibernate.Mapping;

public class RegionMappingClass : ClassMap<Region>  
{
    public RegionMappingClass()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        Map(x => x.Name).Not.Nullable().Length(50);
        HasMany<Region>(x => x.SubRegion).KeyColumn("ParentRegionId").Cascade.All();
    }
}

Fixture / Persistence Specification

using System;  
using System.Collections.Generic;  
using Domain;  
using FluentNHibernate.Testing;  
using NUnit.Framework;

[TestFixture]
[Category("DataIntegration")]
public class RegionMappingFixture : IntegrationTestBase  
{
    [Test]
    public void CanCreateRegions()
    {
        var region = new Region()
                         {
                             Name = "Gtr Manchester"
                         };

        Session.Save(region);

        region.SubRegion.Add(new Region() {Name = "Test B"});
        region.SubRegion.Add(new Region() {Name = "Test C"});

        Session.Save(region);

        FlushAndClear();

        Assert.NotNull(region.Id);
    }

    [Test]
    public void CanMapRegion()
    {
        new PersistenceSpecification<Region>(Session)
            .CheckProperty(x => x.Name, "Gtr Manchester")
            .CheckList(x => x.SubRegion, new List<Region> {new Region() {Name = "Bolton"}, new Region() {Name = "Bury"}})
            .VerifyTheMappings();
    }
}

Small caveat; this code is supplied as a sample, the tests here are the minimum and nothing more

Chris McKee

Chris McKee

https://chrismckee.co.uk

Software Engineer, Web Front/Backend/Architecture; all-round tech obsessed geek. I hate unnecessary optimism

View Comments