使用Fluent NHibernate映射泛型类

时间:2014-10-14 12:01:32

标签: generics fluent-nhibernate mapping

我已阅读http://ayende.com/blog/2951/nhibernate-and-generic-entities,现在有一个问题是可能(如果可能的话,如何)在我的代码中使用流畅的NHibernate映射泛型类:

public interface IEntity
{
    int Id { get; set; }
}

public class FieldEntity<T> : IEntity 
{
    public int Id { get; set; }
    public virtual string FieldType { get; set; }
    public virtual string FieldValue { get; set; }
    public virtual bool IsDeleted { get; set; }

    public FieldEntity(T value)
    {
        FieldType = typeof (T).ToString();
        FieldValue = value.ToString();
    }

    public FieldEntity()
    {
        FieldType = typeof(T).ToString();
    }
} 

1 个答案:

答案 0 :(得分:2)

这是可能的,但你必须映射你想要的每个通用参数。所以重构你的例子:

public abstract class Field : IEntity
{
    public int Id { get; set; }
    public virtual bool IsDeleted { get; set; }
    public abstract string ValueAsString { get; set; }
}

public class PrimitiveField<T> : Field
{
    public virtual T Value { get; set; }
    public override string ValueAsString
    {
        get { return Convert.ToString(CultureInfo.InvariantCultuere); }
        set { Value = Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCultuere); }
    }
}

public class ComponentField : Field
{
    public virtual Component Value { get; set; }
    public override string ValueAsString
    {
        get { return Value.ToString(); }
        set { Value = Component.Parse(value); }
    }
}


public class FieldMap : ClassMap<Field>
{
    public FieldMap()
    {
        Id(x => x.Id).GeneratedBy.Whatever();
        Map(x => x.IsDeleted);
        Map(x => x.ValueAsString, "FieldValue");
        DiscriminateSubClassesOnColumn("FieldType");
    }
}

public class IntFieldMap : SubclassMap<PrimitiveField<int>>
{
    public IntFieldMap()
    {
        DiscriminatorValue("Int32");
    }
}
public class StringFieldMap : SubclassMap<PrimitiveField<string>>
{
    public StringFieldMap()
    {
        DiscriminatorValue("String");
    }
}

public class ComponentFieldMap : SubclassMap<ComponentField>
{
    public ComponentFieldMap()
    {
        DiscriminatorValue("Component");
    }
}