将抽象基类属性映射到多个表(每个派生类一个)

时间:2013-01-22 22:10:57

标签: .net nhibernate fluent-nhibernate nhibernate-mapping fluent-nhibernate-mapping

我正在使用流畅的nhibernate,我正在尝试将我的抽象基类中的属性映射到某个表,该表依赖于派生类的内容。

public class UnmappedClass : Entity<Guid>
{
    // This class isn't mapped to a table on its own, its mapping depends on the class that uses it
}

public abstract class BaseClass : Entity<Guid>
{
    // mapping depends on derived class, not mapped to anything in base class
    protected IList<UnmappedClass> myList = new List<UnmappedClass>();

    public virtual IEnumerable<UnmappedClass> Stuff
    {
        get { return myList.ToList(); }
    }
}

public class DerivedClass : BaseClass
{
    // At this point, I need to map MyClass in member myList to a table specific to DerivedClass
}

我在覆盖中尝试了以下操作并收到错误Invalid object name 'UnmappedClass'.

mapping.HasMany(Reveal.Member<DerivedClass, IEnumerable<UnmappedClass>>("myList"))
    .Table("TableName")
    .Access.Field()
    .Cascade.AllDeleteOrphan()
    .Inverse();

1 个答案:

答案 0 :(得分:0)

我不完全确定,如果这是你想要的,但是如何使用Generics?这是一个例子:

public abstract class BaseClass<T> : Entity<Guid>
    where T : UnmappedClass
{
    // mapping depends on derived class, not mapped to anything in base class
    protected IList<T> myList = new List<T>();

    public virtual IEnumerable<T> Stuff
    {
        get { return myList.ToList(); }
    }
}

public class DerivedClass : BaseClass<MyClass>
{
}

您的映射类也是通用基类:

public abstract class BaseClassMap<TEntity, TList> : ClassMap<TEntity>
    where TEntity : BaseClass
    where TList : UnmappedClass
{
    protected BaseClassMap()
    {
        HasMany(Reveal.Member<TEntity, IEnumerable<TList>>("myList"))
            .Table("TableName")
            .Access.Field()
            .Cascade.AllDeleteOrphan()
            .Inverse();
    }
}

public class DerivedClassMap : BaseClassMap<DerivedClass, MyClass>
{
}

如果代码编译,我没有检查。您应该获取DerivedClass的表,该表由MyClass表(名为“TableName”)引用。