I have come across a weird problem concerning composite keys and one-to-many relationship.
I have the following Invoice class:
public class Invoice: AccountingBase<InvoiceItem>
{
public virtual IList<InvoiceItem> InvoiceItems {.....}
}
the class it inherits is (AccountingBase) is as follows:
public abstract class AccountingBase<TItemType> : AccountingBase where TItemType : AccountingItemBase
{
public virtual ObservableCollection<TItemType> Items { get; set; }
public abstract void AddItem(TItemType item);
}
And the bottom class is:
public abstract class AccountingBase
{
public virtual Subsidiary Subsidiary {....}
public virtual int ID{ ....}
}
The Mapping for Invoice class is as follows:
<class name="Invoice" table="Invoice">
<composite-id>
<key-many-to-one class="Subsidiary" name="Subsidiary"/>
<key-property name="ID" column="InvoiceID" />
</composite-id>
<bag name="InvoiceItems" table="InvoiceItem" inverse="true" lazy="false">
<key>
<column name="Subsidiary" />
<column name="InvoiceID" />
</key>
<one-to-many class="InvoiceItem" />
</bag>
</class>
Now when i retrieve a list of Invoices it works fine, including lazily loading each Items object. The problem i get is, when i select an invoice to edit. I open a new session, and i try retrieve the same invoice using the new session, but when it loads the invoice, it doesnt load the items, it retrieves them as blank, although when i run the generated SQL manually it runs perfectly fine. What could be the reason?
The code i am running to retrieve to get the new Invoice object in the new session using the old object is:
Invoice = Session.Get<Invoice>(invoice);
When i debug, invoice is of Type Invoice, and also, invoice has 1 InvoiceItem in InvoiceItems collection, but the new instance in Invoice, all the fields are populated but the InvoiceItems is null. Is there anything i should know about Nhibernate that might cause this kind of error?
I have tried lazy="false".
Found the fix, i had to correctly implement Equality methods, in both Invoice class and Subsidiary class.