NHibernate映射返回null值

时间:2015-02-05 11:20:33

标签: nhibernate fluent-nhibernate nhibernate-mapping

我在NHibernate中有映射问题。

Order表格的Invoice_Id列是FK表格的可空Invoice

问题是,当我在Invoice表中加载Id存在Order时,我看到ConnectedOrder属性为空,为什么?

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();
    }
}

修改

我改变了我的课程和映射,如RadimKöhler所说,然后我找到了那个主题 Fluent NHibernate One-To-Many Mapping

并且还需要添加:

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

现在可行了

1 个答案:

答案 0 :(得分:2)

您可能不喜欢它,但上面描述的表结构并不代表您创建的实体关系(所谓的one-to-one

如果一个表包含引用另一个表(FK)的列,我们有方案:

  • 每个订单只有一个(或空)发票。 many-to-one
  • 发票可由无或一个或多个订单引用。 one-to-many

这意味着,我们应该表达这样的实体:

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

映射应该是:

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();
    ...