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

1 Answer 1

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();
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.