Question

I've got three tables which share a lot of columns, so I thought to use inheritance to map them and make my data layer a bit more OOP, DRY and so on. In all of the three strategies for inheritance mapping mentioned on NHibernate manual (table per class hierarchy, table per subclass and table per concrete class) the superclass (or common interface) is mapped with an Id that is common to all derived subclasses. BUT none of the primary keys columns on my tables are called the same. Any idea how could I map this?

In a diagram:

TAXTYPE_1

  • clcpnd -> Differently named Id column
  • clcnmb -> Common but differently named column
  • clcprc -> Specific column, unique to this table

TAXTYPE_2

  • rndind -> Differently named Id column
  • rndamb -> Common but differently named column
  • rndorc -> Specific column, unique to this table

TAXTYPE_3

  • dasfnd -> Differently named Id column
  • dastmb -> Common but differently named column
  • dascrc -> Specific column, unique to this table

(Yes my columns are named like that. Old system. Can't change it. Kill me now, please)

EDIT: I've made the schema clearer. Also, I want to make my point somewhat clearer: the three tables are of the same type, and I'd like to be able to abstract a supertype implementing the common fields and then write the specifics into each subclass. So I'd have a TaxType class and a TaxType1, TaxType2 and TaxType3 subclasses, and each one of them "is a" TaxType. Also, this would make my other layers easier to use since I'd do queries with a single TaxType repository and so on. Thanks to Jamie Ide for making me realize how badly was the question asked.

Was it helpful?

Solution

As discussed in the comments: The problem here is the existing ID generation strategy. While one value of the ID (e.g. 1) can be used in all tables, NHibernate mechanism for inheritance can not be used.

The base, abstract class TaxType requires unique ID's among its subtypes, to distinguish each instance.

OTHER TIPS

It's a common mistake to use inheritance because your objects share properties. Inheritance is appropriate when your objects have shared behavior and/or have an "is-a" relationship (e.g. car is a vehicle). Also consider how you will query for the objects; do you need to query for a base class and have NHibernate return any derived class?

An interface may be a better choice in your case. This also resolves the differently named Id columns because you can define a property named Id that accesses the actual column.

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

public class MyClass : IMyEntity
{
    public int Clcnmb { get; set; }
    public int Id
    { 
        get { return Clcnmb; }
        set { Clcnmb = value; }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top