NHibernate:使用通用枚举属性映射类

时间:2012-02-14 09:54:49

标签: c# .net nhibernate enums nhibernate-mapping

我有一个像这样定义的类:

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; }
}

State属性是枚举的地方:

public enum CarState
{
    Stopped = 1,
    Moving = 2
}
public enum OrderState
{
    Ordered = 1,
    Delivered = 2
}

我可以有两种类型:

StateMachineMetadata<CarState>, StateMachineMetadata<OrderState>

使用NHibernate在一个StateMachineMetadata中保留?

=== update ===

由于变通方法通用部分可以移动到界面:

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; }
}

1 个答案:

答案 0 :(得分:3)

,这就是原因。

假设我们在StateMachineMetadata表中有两行:

ID | State | DateChanged
1  |   1   |  2012-02-13
2  |   1   |  2012-02-14

如果State列同时映射到CarStateOrderState,NHibernate将如何确定要反序列化的枚举?一种解决方案是将一个鉴别器列添加到StateMachineMetadata表中,该表告诉NHibernate它应该将特定行映射到哪个类型。
例如Type鉴别器列:

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>