Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Nhibernate - mapping a collection of components (value objects)?

I am currently using component maps like this:

public class UserMapping
{
         public UserMapping()
         {
            Id(c => c.Id).GeneratedBy.HiLo("100");
            Map(c => c.UserName);
            Component(c => c.Country, CountryComponentMapping.Map);
         }
}


public sealed class CountryComponentMapping
{
    public static void Map(ComponentPart<Country> part)
    {
        part.Map(x => x.CountryName)
        part.Map(x => x.CountryAlpha2)
    }
}

I like this becuase I only have to define the mapping for the component/value object in one place.

How would I go about using the same semantics for a collection of the component? (e.g. lets assume we wanted to change this to a collection of countries on the user entity)

like image 367
UpTheCreek Avatar asked Nov 18 '10 11:11

UpTheCreek


People also ask

What is NHibernate mapping?

NHibernate is an object–relational mapping (ORM) solution for the Microsoft . NET platform. It provides a framework for mapping an object-oriented domain model to a traditional relational database.

What is the difference between NHibernate and fluent NHibernate?

Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.

What is bag in NHibernate?

A bag is an unordered, unindexed collection which may contain the same element multiple times. The . NET collections framework lacks an IBag interface, hence you have to emulate it with an IList. NHibernate lets you map properties of type IList or ICollection with the <bag> element.


1 Answers

You can map this as a Component Collection. Unfortunately there is no overload to HasMany().Component() in Fluent NHibernate that allows you to specify that you want to use a derived class of ComponentMap. You can use a modification of your technique above though.

public sealed class UserMap : ClassMap<User> {
    public UserMap() {
        Id(c => c.Id).GeneratedBy.HiLo("100");
        Map(x => x.Name);
        HasMany(x => x.Countries).Component(CountryComponentMapping.Map);
    }
}

public sealed class CountryComponentMapping {
    public static void Map(CompositeElementBuilder<Country> part) {
        part.Map(x => x.CountryName);
        part.Map(x => x.CountryAlpha2)
    }
}
like image 60
James Kovacs Avatar answered Sep 29 '22 20:09

James Kovacs