2011-12-08 66 views
1

通過流利nhibernate,我不能使用automapping與約定,因爲它添加額外的外鍵到關係的表。這個問題在stackoverflow.com/questions/6091654/fluentnhibernate-automapping-onetomany-relation-using-attribute-and-convention/7867516FluentNHibernate:Automapping OneToMany關係

詳細解釋但是正如你所看到的,它是通過使用屬性來解決的。我的問題是:

我不想在模型屬性上使用屬性。因爲在接下來的幾年裏我們可能不會在項目中使用nhibernate。所以我不想觸摸模型。沒有KeyColumnAttribute的問題的解決方案。

感謝

回答

0
class BiDirectionalHasManyConvention : IReferenceConvention, IHasManyConvention 
{ 
    public void Apply(IOneToManyCollectionInstance instance) 
    { 
     // looks for a Property which references the type containing the collection 
     var referenceProperty = instance.ChildType.GetProperties() 
      .First(prop => prop.PropertyType == instance.EntityType); 

     instance.Key.Column(referenceProperty.Name + "Id"); 
    } 

    // Optional, just to make sure the foreignkey column is propertyname + "Id" 
    public void Apply(IManyToOneInstance instance) 
    { 
     instance.Column(instance.Name + "Id"); 
    } 
} 
+0

會發生什麼,如果地址類有另一個人的類型,比如'公共虛者UpdatedBy {獲得;組; '在所有者屬性旁邊。 使用IReferenceConvention時,已經描述了該屬性的名稱,爲什麼流利地使用IHasManyConvention來重命名它。 – whitestream

+0

而在person.Addresses生成的select語句中,它添加了兩個相同的字段。一個來自參考約定,另一個來自hasmany約定。例如:選擇ownerid作爲第一,adressid,ownerid作爲第二個從ownerid =?的地址。 – whitestream

+0

@whitestream記住你,NH是用最尷尬的模式編寫的,所以它不會假設它總是一個簡單的雙向,但可能有:1)多於一個對父對象的引用2)引用指向另一個對象父親3)參考點指向繼承 - hirarchy ...所以最簡單的方法是將多對一和一對多作爲完全獨立的事物,因此選擇id兩次。 – Firo