0

I have two classes, one inheriting from the other. The first shows a summary view of data (4+ columns) and the child shows a detail view (40+ columns). Both classes are accessing the same table and share the same columns being accessed.

Can my child class inherit from the parent class so I only have to change mappings in one place? I'd rather not have duplicate code running rampant.

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

I want to do something like this:

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
ps2goat
  • 8,067
  • 1
  • 35
  • 68

1 Answers1

1

If you want the Child to be a subclass of parent in db also, you'll need a discriminator column.

If you just want to reuse code then share a mapping base class

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
    }
}
Firo
  • 30,626
  • 4
  • 55
  • 94
  • This is similar to what I was doing, but NHibernate seems to be returning child objects when my domain context specifies the parent object. NHibernate's query includes the properties that are only on the child object... – ps2goat May 15 '13 at 14:48
  • I made some changes and it works, so far. I'll report back with other issues. – ps2goat May 15 '13 at 16:32
  • when you mapped the Parent as base class then of course it will return all Parent objects and Child objects are Parent objects, too. – Firo May 16 '13 at 05:31
  • Because the parent was a summary of the data and the child was detailed data (both using the same table with no discriminator), All objects were being returned as child objects. That defeated the purpose of what I was trying to achieve. I ended up having another class inherit the parent and used that class as the object for summaries, and am continuing to work with the detail objects. Detailed objects _will_ have discriminators. – ps2goat May 16 '13 at 16:23