0

I have a database with a field 'LS_GENDER' which stores genders as 'M' or 'F'.

My application uses an enumeration called Gender to work with genders.

My entity has the following field and property:

private string _gender;

public Gender Gender { get { return GetGenderFromString(_gender); } };

private Gender GetGenderFromString(string strGender)
{
  switch (strGender.ToLower())
  {
    case "f":
      return Gender.Female;
    case "m":
      return Gender.Male;
    default:
      return Gender.Unknown;
  }
}

How do I map this with FluentNHibernate? I am trying to use field access (as shown below):

Map(x => x.Gender).Column("LS_GENDER").Access.CamelCaseField(Prefix.Underscore);

but I'm getting the error 'Can't parse F as Gender'. I think NHibernate is getting confused because the property and field are not of the same type.

How should I map this?

David
  • 15,750
  • 22
  • 90
  • 150

3 Answers3

0

I guess you are mapping a database string value (M,F,U) to an enumeration.

The answer to this question may help you map enumerations to string values.

How do you map an enum as an int value with fluent NHibernate? Mapping custom enum classes with Fluent Nhibernate

You could use a custom type to map the strings (M,F,U) to the enumeration you've got.

On your enumeration class using a custom attribute to specify its string value. The following article may help you how to do this.

http://david.gardiner.net.au/2007/11/using-enum-types-with-nhibernate.html

Hope that helps.

Community
  • 1
  • 1
Aim Kai
  • 2,934
  • 1
  • 22
  • 34
  • Thanks for your response. I don't think the first link is really relevant. The second link is a potential solution, but involves invasive coding outside my NHibernate implementation - e.g. adding custom attributes to the Gender enumeration. I should be able to solve this within NHibernate itself. I'm currently using a custom IPropertyAccessor, but I don't seem to be able to get it to work... – David Nov 19 '10 at 10:41
0

To my considerable astonishment, this mapping worked:

Map(x => x.Gender).Column("LS_GENDER").Access.CamelCaseField(Prefix.Underscore).CustomType(typeof (string));

So the mapping says 'access the field directly and treat it as a string, even though the corresponding property is of type Gender'.

David
  • 15,750
  • 22
  • 90
  • 150
  • Ah, but then I can't do Linq queries on the Gender. I get: Type mismatch in NHibernate.Criterion.SimpleExpression: Deceased.Gender expected type System.String, actual type Kctc.Gender – David Nov 19 '10 at 11:32
  • Maybe provide your own custom type? – Aim Kai Nov 19 '10 at 14:42
0

You map a private field using reveal:

Map(Reveal.Member<ClassType>("_gender")).Column("LS_GENDER");

But that doesn't resolve your LINQ problem because now NHibernate doesn't know about the Gender property. To resolve both issues I would use a custom user type that implements IUserType.

Jamie Ide
  • 48,427
  • 16
  • 81
  • 117