views:

168

answers:

1

I have two similar tables:

Table1:

[ id ] | [ name ]

Table2:

[ id ] | [ name ]

and I need to read/write data using only one class:

public class TwinTable
{
   public virtual int Id { get; set; }
   public virtual string Name1 { get; set; }
   public virtual string Name2 { get; set; }
}

Plus one of the tables may or may not have an entity with the specified Id, and both tables may or may not have entities, so Name1 can be null and Name2 can be null and both of them can be null.

I can not change the structure of the DB, and it's not a good thing if i have to add something to it.

Hope for your help!

A: 

One solution is to map Table1 to a class, and then map Table2 as a joined-subclass of Table1. The joined subclass will then be like your TwinTable as you described above:

<class name="Class1" table="Table1" >
  <id name="Id" column="id">
    <generator class="identity" />
  </id>
  <property name="Name1" column="name" not-null="true" />
</class>

<joined-subclass name="Class2" table="Table2">
  <key column="Id" />
  <property name="Name2" column="name" not-null="true" />
</joined-subclass>
Kevin Albrecht
but.. I see that the key-column of the joined-subclass is "Id". so i guess if there is NO entry in Table1 with Id = 1 and there IS an entry in Table2 with Id = 1, then TwinTable instance will be null as Table2 cannot be joined to null.. am i wrong?
npeBeg
That is correct. You may also want to consider using a union-subclass, which is well described here: http://nhforge.org/blogs/nhibernate/archive/2009/04/10/nhibernate-mapping-inheritance.aspx
Kevin Albrecht

related questions