Nhibernate和继承代码映射

时间:2013-05-13 22:08:30

标签: vb.net nhibernate mapping-by-code

我有两个类,一个继承自另一个。第一个显示数据的摘要视图(4列以上),子显示详细视图(40多列)。这两个类都访问同一个表并共享正在访问的相同列。

我的子类可以从父类继承,所以我只需要在一个地方更改映射吗?我宁愿没有重复的代码运行猖獗。

E.g:

Public Class Parent
 Public Overridable Property MyProp As String
 Public Overridable Property MyProp2 As String
End Class

Public Class Child : Inherits Parent
 Public Overridable Property MyProp3 As String
End Class

我想做这样的事情:

Public Class ParentMapping
    Inherits ClassMapping(Of Parent)
Public Sub New()
 Me.Property(Function(x) x.MyProp, Sub(y) y.column("MyProp"))
 Me.Property(Function(x) x.MyProp2, Sub(y) y.column("MyProp2"))
End Sub
End Class

Public Class ChildMapping
Inherits SubClassMapping(of Child)
 Public Sub New()
  ' I want to be able to inherit the mappings of the parent here.
  MyBase.New()

  Me.Property(Function(x) x.MyProp3, Sub(y) y.column("MyProp3"))
 End Sub
End Class

1 个答案:

答案 0 :(得分:1)

如果你希望Child也是db中父类的子类,你需要一个鉴别器列。

如果您只想重用代码,则共享映射基类

public abstract class ParentChildMapping<T> : ClassMapping<T> where T : Parent
{
    public ParentChildMapping()
    {
    // map shared properties here
    }
}

public class ParentMapping : ParentChildMapping<Parent>
{
}

public class ChildMapping : ParentChildMapping<Child>
{
    public ChildMapping()
    {
    // map additional properties here
    }
}