Belter Logo

Many To Many Mapping in Fluent NHibernate

October 11, 2011

Here’s a spot of code for mapping two classes in Fluent NHibernate with a many to many relation. Say you have Employee and Department classes like so.

public class Actor
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList Movies { get; set; }
}

public class Movie
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList Actors { get; set; }
}

So obviously a movie can have many actors and an actor could star in multiple movies. Your database will consist of three tables, an actors, a movie and a Cast table. The cast table will pretty much just be our link with ActorId and MovieId foreign keys.

Finally here’s the mapping.

public class ActorMap : ClassMap
{
    public ActorMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);

        HasManyToMany(x => x.Movies)
            .WithTableName("Cast")
            .WithParentKeyColumn("ActorId")
            .WithChildKeyColumn("MovieId")
            .LazyLoad()
            .Cascade.SaveUpdate();
    }
}

public class MovieMap : ClassMap
{
    public MovieMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);

        HasManyToMany(x => x.Actors)
            .WithTableName("Cast")
            .WithParentKeyColumn("ActorId")
            .WithChildKeyColumn("MovieId")
            .Inverse();
    }
}

Duncan McDougall

Duncan McDougall is contract web developer from Annan, Scotland.
Twitter LinkedIn GitHub