I have an inherited class structure with multiple table. My class structure is as follows. (This is not the real classes. I have created fake classes which imitate the originals here to save space.)
class Account {
public virtual int AID { get; set; }
public virtual string Name { get; set; }
public virtual string Serial { get; set; }
public virtual string Type { get; set; }
public Account { Type = "Default"; }
}
class Human : Account {
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
// more properties..
public Human { Type = "Human"; }
}
class Bank : Account {
public virtual string BranchName { get; set; }
// more properties..
public Bank { Type = "Bank"; }
}
My Account.hbm.xml file looks like below.
<class name="Account">
<id name="AID" type="Int32">
<generator class="native" />
</id>
<discriminator column="Type" type="string" />
<property name="Name" />
<property name="Serial" />
<property name="Type" />
<subclass name="Human" discriminator-value="Human">
<join table="Account">
<key column="AID" />
<property name="FirstName" />
<property name="LastName" />
</join>
</subclass>
<subclass name="Bank" discriminator-value="Bank">
<join table="Account">
<key column="AID" />
<property name="LocationName" />
</join>
</subclass>
</class>
I execute this and tables are created with the correct set of fields. Problem is when I insert the record.
I do it as of below.
Bank bank = new Bank();
bank.Name = "Any Name";
bank.Serial = "0001";
bank.BranchName = "Local CIty";
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(bank);
transaction.Commit();
}
}
Below is the error produced by NUnit. Maybe I am doing somehting wrong. Can any one help me on this please?
NHibernate.PropertyValueException : Error dehydrating property value for
xxxx.xxxxx.Bank.Name
----> System.IndexOutOfRangeException : Parameter index is out of range.
I modified the Account.hbm.xml mapping file with cluase. Now the things work fine. I can smoothly insert records now without any errors.
Here is the working mapping file.
<class name="Account">
<id name="AID" type="Int32">
<generator class="native" />
</id>
<!-- <discriminator column="Type" type="string" /> -->
<property name="Name" />
<property name="Serial" />
<property name="Type" />
<joined-subclass name="Human" table="Human">
<key column="AID" />
<property name="FirstName" />
<property name="LastName" />
</subclass>
<joined-subclass name="Bank" table="Bank">
<key column="AID" />
<property name="LocationName" />
</subclass>
</class>
I thought may be discriminator clause might be helpful and overused. :) Without it works fine.