2013-05-13 148 views
0

我有兩個類,一個從另一個繼承。第一個顯示數據的概要視圖(4列以上),而孩子顯示詳細視圖(40列以上)。這兩個類都訪問同一個表並共享被訪問的相同列。Nhibernate並繼承按代碼映射

我的孩子類可以從父類繼承,所以我只需要在一個地方更改映射?我寧願沒有重複的代碼運行猖獗。

如:

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

如果你希望孩子成爲分貝還父的子類,你需要一個鑑別列。

如果你只是想重用代碼然後共享的映射基類

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 
    } 
} 
+0

這與我在做什麼,但NHibernate的似乎回到孩子時,我的域範圍內指定的父對象的對象。 NHibernate的查詢包括只在子對象上的屬性... – ps2goat 2013-05-15 14:48:13

+0

到目前爲止,我做了一些更改並且它可以工作。我會回報其他問題。 – ps2goat 2013-05-15 16:32:14

+0

當你將Parent映射爲基類時,它當然會返回所有Parent對象,並且Child對象也是Parent對象。 – Firo 2013-05-16 05:31:52