NHibernate 3.2 Mapping by Code: Component Mapping

12 Oct 2011 by

Component mapping in NHibernate 3.2 Mapping by code provides a very flexible way. You can have multiples static method for returning Action<IComponentMapper<Address>> for the same component class. So that you can reuse it in different place with more customization.

In this example, we have Veteran class and Address class as a component.

 

Entity class files

Address.cs

  public class Address
  {
    public virtual string HouseNo { get; set; }
    public virtual string Street { get; set; }
    public virtual string Commune { get; set; }
    public virtual string District { get; set; }
    public virtual string Province { get; set; }
  }

Veteran.cs

  public class Veteran
  {
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Address Address { get; set; }
  }

Entity mapping class files

AddressMap.cs

  public class AddressMap
  {
    public static Action<IComponentMapper<Address>> Mapping()
    {
      return c =>
               {
                 c.Property(p => p.HouseNo);
                 c.Property(p => p.Street);
                 c.Property(p => p.Commune);
                 c.Property(p => p.District);
                 c.Property(p => p.Province);
               };
    }
  }

VeteranMap.cs

  public class VeteranMap : ClassMapping
  {
    public VeteranMap()
    {
      Id(p=>p.Id, map=>map.Generator(Generators.GuidComb));
      Property(p=>p.Name);
      Component(p=>p.Address, AddressMap.Mapping());
    }
  }

3 responses so far

  • Rui says:

    Hello, imagine the following:

    public class Style
    {
    public virtual int IdStyle { get; set; }
    public virtual ColorObj BackgroundColor { get; set; }
    public virtual ColorObj Color { get; set; }
    }

    public class ColorObj
    {
    public virtual int R { get; set; }
    public virtual int G { get; set; }
    public virtual int B { get; set; }
    }

    public class ColorObjMap
    {
    public static Action<IComponentMapper> Mapping()
    {
    return c =>
    {
    c.Property(x => x.R);
    c.Property(x => x.G);
    c.Property(x => x.B);
    };
    }
    }

    This will only create a R column (R,G,B) not one for each color :(
    Any ideas?

  • Rui says:

    Found the solution :) (or I think so…)

    Component(x => x.BackgroundColor, ColorObjMap.Mapping(“BackgroundColor”));

    public static Action<IComponentMapper> Mapping(String columnNamePrefix)
    {

    return c =>
    {
    c.Property(x => x.R, m=>m.Column(columnNamePrefix + “R”));
    c.Property(x => x.G, m => m.Column(columnNamePrefix + “G”));
    c.Property(x => x.B, m => m.Column(columnNamePrefix + “B”));
    };
    }

    Thank you, great help 😀

Leave a Reply