gpt4 book ai didi

.net - 在 NHibernate 中映射枚举集合

转载 作者:行者123 更新时间:2023-12-04 02:54:16 26 4
gpt4 key购买 nike

我尝试使用 Fluent NHibernate 在 NHibernate 中映射枚举集合,然后对该枚举集合的内容执行查询,但系统每次都会抛出异常。

我有一个 Widget 类,映射到 Widget 表。还有一个 WidgetType 枚举,Widget 的单个实例可以有许多 WidgetType,通过 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");
}
}

我无法控制数据库架构;架构无法更改。该架构必须存储与 Widget 关联的 WidgetTypes 的整数值,并且不能转换为匹配枚举的字符串版本。我非常努力地保持枚举的强类型,并避免为 Ref 表创建新实体。

其他类具有与“.CustomType(typeof(someTypeEnum)”配置一起使用的基于枚举的类型属性,但是 HasMany 映射上没有 CustomType 属性。使用上面的这个 HasMany 映射,对集合的查询会抛出一个“无法确定成员类型”异常。

这可能吗?属性(property)应该如何设置? Fluent 映射应该如何配置?我如何查询集合(我的查询只需要 Any 或 Contains 的等价物)?

最佳答案

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
}

并像这样设置它(应该也适用于 Fluent 映射):

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 值。

关于.net - 在 NHibernate 中映射枚举集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3806518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com