nhibernatefluent-nhibernatemappingiusertype

Map custom type in FluetnNhibernate


I have 2 classes.

public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Person
{
    public virtual Name Name { get; set; }
    public virtual int Age { get; set; }
}

I want to map Person to database like this:

| First Name | LastName | Age |

I tried to create IUserType implementation for Name. But here

public SqlType[] SqlTypes
    {
        get { return new[] { new SqlType(DbType.String), new SqlType(DbType.String) }; }
    }

I have an exception

property mapping has wrong number of columns

Solution

  • What you're actually asking for is a Component:

    https://github.com/jagregory/fluent-nhibernate/wiki/Fluent-mapping#componentmap

    Your class maps would look like:

    public class NameComponent : ComponentMap<Name>
    {
        public NameComponent()
        {
            Map(x => x.FirstName);
            Map(x => x.LastName);
        }
    }
    
    public class PersonMap : ClassMap<Person>
    {
        public PersonMap()
        {
            Id(x => x.Id)...
            Map(x => x.Age);
            Component(x => x.Name);
        }
    }
    

    That will map the FirstName/LastName to the same person table as two separate columns. But give you a single Name object on your Person.


    If you need to AutoMap the component, take a look at this blog:

    https://web.archive.org/web/20190212181857/http://www.jagregory.com:80/writings/fluent-nhibernate-auto-mapping-components/