2

I have a problem with mapping in NHibernate.

The Order table has the Invoice_Id column which is the nullable FK to the Invoice table.

The problem is, when I load an Invoice which Id exists in the Order table, I see that ConnectedOrder property is null, why?

public class Invoice
{
    public virtual Order ConnectedOrder { get; set; }
}

public class Order
{
    public virtual Invoice ConnectedInvoice { get; set; }
}


public class InvoiceMap : ClassMap<Invoice>
{
    public InvoiceMap()
    {
        this.References(x => x.ConnectedOrder).Nullable();
    }
}

public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        this.References(x => x.ConnectedInvoice).Nullable();
    }
}

edit

I've changed my classes and mappings like Radim Köhler said, then I found that topic Fluent NHibernate One-To-Many Mapping

and there was the need to also add:

this.HasMany(x => x.Orders)
    .KeyColumn("Invoice_id")
    .Inverse()
    .Cascade
    .AllDeleteOrphan();

and now it works

Community
  • 1
  • 1
Tony
  • 12,405
  • 36
  • 126
  • 226

1 Answers1

2

You may not like it, but the table structure described above, is not representing Entity relations you've created (so called one-to-one).

In case, that one table contains column referencing the another table (FK), we have scenario:

  • Each Order has exactly one (or null) Invoice. (many-to-one)
  • Invoice can be referenced by none or one or many Orders. (one-to-many)

That means, that we should express Entities like this:

public class Invoice
{   // many orders could reference us
    public virtual IList<Order> Orders { get; set; }
    ...

public class Order
{   // unchanged
    public virtual Invoice ConnectedInvoice { get; set; }
    ...

And the mapping should be:

public InvoiceMap()
{    // HasMany is one-to-many
     this.HasMany(x => x.Orders)
        ...
}
public OrderMap()
{   // References is many-to-one
    this.References(x => x.ConnectedInvoice).Nullable();
    ...
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • thanks for the explanation. I changed the classes but still the found Invoice has the Orders count = 0. I also tried to load all Invoices whose have the Orders count > 0, but none Invoices with that criteria were found – Tony Feb 05 '15 at 11:53
  • Well if you have the mapping as I described, and even more, you explicitly used for `HasMany` the setting `.KeyColumn("Invoice_Id")` and for `References` you have `.Column('Invoice_Id')` ... then if you are inside of one session - and data are there... all will be loaded. (be sure session is not closed). Could you check that all? Mapping above is ok. – Radim Köhler Feb 05 '15 at 11:57