我在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();
现在可行了
答案 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();
...