我尝试使用Fluent NHibernate映射NHibernate中的枚举集合,然后对该枚举集合的内容执行查询,但每次系统都会抛出异常。
我有一个映射到Widget表的Widget类。还有一个WidgetType枚举,一个小部件实例可以有许多通过WidgetTypes属性映射的WidgetTypes。该属性需要映射到一个单独的表WidgetTypeRef,其中包含两个整数列: WidgetId和WidgetType。
public class Widget
{
/* omitted */
public IList<WidgetType> WidgetTypes { get; set; }
}
public enum WidgetType
{
SomeType = 0,
SomeOtherType = 1,
YetOneMoreType = 2
}
public partial class WidgetMapping : IAutoMappingOverride<Widget>
{
public void Override(AutoMapping<Widget> mapping)
{
/* omitted */
mapping.HasMany(w => w.WidgetTypes)
.Table("WidgetTypeRef")
.KeyColumn("WidgetId")
.Element("WidgetType");
}
}我无法控制DB架构;该架构不能更改。架构必须存储与小部件关联的WidgetTypes的整数值,并且不能转换为与枚举的字符串版本匹配。我非常努力地保持枚举的强类型,并避免为Ref表创建新的实体。
其他类具有使用".CustomType(typeof(someTypeEnum)“配置的基于枚举的类型属性,但是在HasMany映射上没有CustomType属性。使用上面的HasMany映射,对集合的查询会抛出“无法确定成员类型”异常。
这有可能吗?应该如何设置该属性?Fluent映射应该如何配置?如何在集合中查询(我的查询只需要等效于Any或Contains)?
发布于 2010-09-28 03:00:14
public class EnumToIntConvention : IUserTypeConvention
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType.IsEnum);
}
public void Apply(IPropertyInstance target)
{
target.CustomType(target.Property.PropertyType);
}
}使用该约定,具有以下枚举:
public enum Status
{
Inactive = 0,
Active = 1,
Canceled = 2
}并像这样设置它(也应该使用流畅的映射):
var cfg = Fluently.Configure()
.Database(configurer)
.Mappings(m =>
{
m.AutoMappings.Add(AutoMap.Assemblies(Assembly.GetExecutingAssembly())
.Where(type => AutomapAssemblies.Contains(type.Namespace))
.Conventions.Add<EnumToIntConvention>() // Magic code goes here!
.Conventions.Add());
});将保存integer值而不是string值。
https://stackoverflow.com/questions/3806518
复制相似问题