开发者

FluentNHibernate: how to access field which has datatype different to property

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(开发者_JS百科"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?


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.


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.


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'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜