NHibernate:具有通用枚举属性的映射类
作者:互联网
我有一个这样定义的类:
public class StateMachineMetadata<T> where T: struct
{
public virtual int ID { get; protected set; }
public virtual T State { get; set; }
public virtual DateTime DateChanged { get; set; }
}
如果国家财产是枚举:
public enum CarState
{
Stopped = 1,
Moving = 2
}
public enum OrderState
{
Ordered = 1,
Delivered = 2
}
我可以有两种类型:
StateMachineMetadata<CarState>, StateMachineMetadata<OrderState>
使用NHibernate保留在一个表StateMachineMetadata中?
===更新===
解决方法通用部分可以移至接口:
public interface IStateMachineMetadata<T> where T: struct
{
int ID { get; }
T State { get; set; }
DateTime DateChanged { get; set; }
}
public class StateMachineMetadataBase
{
public virtual int ID { get; protected set; }
public virtual DateTime DateChanged { get; set; }
}
public class CarStateMachineMetadata
: StateMachineMetadataBase, IStateMachineMetadata<CarState>
{
public virtual CarState State { get; set; }
}
解决方法:
不,这就是原因.
假设我们在StateMachineMetadata表中有两行:
ID | State | DateChanged
1 | 1 | 2012-02-13
2 | 1 | 2012-02-14
如果State列同时映射到CarState和OrderState,NHibernate将如何确定反序列化到的枚举?一种解决方案是在StateMachineMetadata表中添加一个鉴别符列,该列告诉NHibernate它应该将特定行映射到哪种类型.
例如类型鉴别符列:
ID | State | DateChanged | Type
1 | 1 | 2012-02-13 1
2 | 1 | 2012-02-14 2
告诉NHibernate第一行代表StateMachineMetadata< CarState>.而第二个是StateMachineMetadata< OrderState>.这在NHibernate中称为Table per class hierarchy mapping.它要求两个类都从一个公共基类继承,在您的情况下,该基类自然是StateMachineMetadata T.
但是这里有个问题:NHibernate没有办法用开放的泛型类型映射一个类.原因是it’s simply not possible.
但是,NHibernate确实允许您使用封闭的泛型映射类.您只是不能将它们映射到同一张表.这样的配置如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="MyAssembly"
namespace="MyNamespace">
<class name="StateMachineMetadata`1[MyNamespace.CarState]"
table="StateMachineMetadata_CarState">
<!-- property to column mappings -->
</class>
<class name="StateMachineMetadata`1[MyNamespace.OrderState]"
table="StateMachineMetadata_OrderState">
<!-- property to column mappings -->
</class>
</hibernate-mapping>
标签:enums,nhibernate,nhibernate-mapping,c,net 来源: https://codeday.me/bug/20191201/2083043.html