views:

60

answers:

1

I have a database table that includes a two bit fields: IsEvenSide and IsOddSide. I want this to map to the following enum:

[Flags] enum SideOfStreet { None, Even, Odd }

I have done IUserType's in the past, but I don't know how to map to multiple database fields.

How can this be done?

P.S.: I'm using Fluent NHibernate, but I'm okay with an hbm solution as well. I'll just figure out how to convert it.

+1  A: 

Map the database fields to read only properties in your class:

Map(x => x.IsEvenSide);
Map(x => x.IsOddSide);

And control them through a public property:

[revised version to work with flag enumeration]

public class Example
{

    public IsEvenSide { get; private set; }
    public IsOddSide { get; private set; }

    public SideOfStreet SideOfStreet
    {
        get
        {
            var side = SideOfStreet.None;
            if (IsEvenSide) { side |= SideOfStreet.Even; }
            if (IsOddSide) { side |= SideOfStreet.Odd; }
            return side;
        }
        set
        {
            IsEvenSide = (value & SideOfStreet.Even) == SideOfStreet.Even;
            IsOddSide = (value & SideOfStreet.Odd) == SideOfStreet.Odd;
        }
    }
}

If you don't want to expose getters for IsEvenSide and IsOddSide you can mark them private and use Reveal:

Map(Reveal.Property<Example>("IsEvenSide"));
Jamie Ide
Whoops, corrected the question. I typed my problem from memory -- the real system doesn't have a Both option and does use flags.
David Pfeffer

related questions