Search code examples
nhibernatefluent-nhibernatenhibernate-mappingfluent-nhibernate-mapping

Nhibernate mapping different table with same columns


in my DB i have two views with exactly the same columns (each view refer data from a different remote DB via linked server).

Cause both views have same columns, logically represent the same data.

In some situation i need both union of the data stored in the different views but also the single data from each view indipendently.

What is the best mapping to use in this situation? There is a specific map which help me to do the join of the two views in only one entity with a discriminator value?

here an example:

VIEW1

Col1 | Col2

X1 | Y1

X2 | Y2

VIEW2

Col1 | Col2

K1 | Z1

K2 | Z2

Situation 1 - Union of data

VIEW1 U VIEW2 = (X1,X2,K1,K2)(Y1,Y2,Z1,Z2)

Situation 2 - Single data from each view

VIEW1 = (X1,x2)(Y1,Y2)

VIEW2 = (K1,K2)(Z1,Z2)


Solution

  • I would go for a third view defined as the union of your two views (seems like your situation 1), adding a third column Discrim as discriminator value. Let's say value of 1 for View1, value of 2 for View2.

    Then I would go for a 'Table per class hierarchy' inheritance mapping stategy ( http://nhibernate.info/doc/nh/en/index.html#persistent-classes-inheritance section 8.1.1 ) , mapping each subclass to each view rows set, using the discriminator value.

    This way, you could query your whole set of objects though the super class, or only one of the views by querying the corresponding subclass.

    If your views share the same ids, provided ids are int and 0 is not shared, a workaround might be to transform, in you third view, ids coming from View1 to negative numbers and leave positive numbers for ids coming from View2. A convention that you should not forget in your code, if yo plan on storing ids, or , given an id, access the data in another way.