Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate Map to private/protected Field that has no exposing Property

I have the following Person and Gender classes (I don't really, but the example is simplified to get my point across), using NHibernate (Fluent NHibernate) I want to map the Database Column "GenderId" [INT] value to the protected int _genderId field in my Person class. How do I do this?

FYI, the mappings and the domain objects are in separate assemblies.

public class Person : Entity
{
    protected int _genderId;

    public virtual int Id { get; private set; }
    public virtual string Name { get; private set; }

    public virtual Gender Gender
    {
        get { return Gender.FromId(_genderId); }
    }
}

public class Gender : EnumerationBase<Gender>
{
    public static Gender Male
        = new Gender(1, "Male");

    public static Gender Female
        = new Gender(2, "Female");

    private static readonly Gender[] _genders
        = new[] { Male, Female };

    private Gender(int id, string name)
    {
        Id = id;
        Name = name;
    }

    public int Id { get; private set; }
    public string Name { get; private set; }

    public static Gender FromId(int id)
    {
        return _genders.Where(x => x.Id == id).SingleOrDefault();
    }
}
like image 599
Jon Erickson Avatar asked Apr 23 '10 22:04

Jon Erickson


3 Answers

As dotjoe said, I think you need to expose it as a protected property. Then you could get to it using the Reveal mapping.

Your class/mapping will probably look something along the lines of

public class Person : Entity
{
    protected int genderId{ get; set; }
}


public PersonMap : ClassMap<Person>
{  
    public PersonMap()  
    {  
        Map(Reveal.Member<Person>("genderId")) 
    }  
}

There are also similar questions here and here if that helps.

like image 89
Roman Avatar answered Nov 15 '22 23:11

Roman


simply make it a protected property. NH reflection does not require public property.

protected virtual int _genderId { get; set; }

then map like so (sorry never got around to fluent)...

<property name="_genderId" column="genderId" />

also, it might be easier to just map the enum. You can have the column stored as the Enum value or text. Plenty of examples of that.

like image 35
dotjoe Avatar answered Nov 15 '22 23:11

dotjoe


I'm only using nHibernate for the first time, but I believe you don't need to create a protected property for this, you just have to specify access="field" in your mapping and you can map directly to the private field. E.g.

<property name="_genderId" access="field" column="GenderId"  type="Int32" />

This way there's less impact on your domain layer.

like image 1
Mr. Bungle Avatar answered Nov 16 '22 00:11

Mr. Bungle