FluentNHibernate:如何访问数据类型与属性不同的字段
我有一个包含字段“LS_GENDER”的数据库,该字段将性别存储为“M”或“F”。
我的应用程序使用名为 Gender 的枚举来处理性别。
我的实体具有以下字段和属性:
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;
}
}
如何将其映射到 FluentNHibernate?我正在尝试使用字段访问(如下所示):
Map(x => x.Gender).Column("LS_GENDER").Access.CamelCaseField(Prefix.Underscore);
但收到错误“无法将 F 解析为性别”。我认为 NHibernate 很困惑,因为属性和字段不是同一类型。
我应该如何映射这个?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用 reveal 映射私有字段:
但这并不能解决您的 LINQ 问题,因为现在 NHibernate 不能了解性别属性。为了解决这两个问题,我将使用实现 IUserType 的自定义用户类型。
You map a private field using reveal:
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.
我猜您正在将数据库字符串值(M,F,U)映射到枚举。
这个问题的答案可能会帮助您将枚举映射到字符串值。
如何映射枚举作为流畅的 NHibernate 的 int 值?
使用 Fluent Nhibernate 映射自定义枚举类
您可以使用自定义类型将字符串 (M,F,U) 映射到您获得的枚举。
在您的枚举类上使用自定义属性来指定其字符串值。以下文章可能会帮助您了解如何执行此操作。
http://david.gardiner.net。 au/2007/11/using-enum-types-with-nhibernate.html
希望有所帮助。
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:
So the mapping says 'access the field directly and treat it as a string, even though the corresponding property is of type Gender'.