簡體   English   中英

導航屬性名稱與屬性類型不同時,NHibernate多對一/一對多外鍵如何處理?

[英]How to do a NHibernate many-to-one/one-to-many foreign key in case of navigation property name different from property type?

我正在將NHibernate / FluentNhibernate與AutoMapping配置一起使用,但是在某些關系的外鍵上遇到了麻煩。 特別是那些導航屬性名稱與其指向的類型名稱不同的屬性:

public class Country       
{
    public virtual string Code { get; set; }

    public virtual string Name { get; set; }

    public virtual Currency DefaultCurrency { get; set; }
}

public class Currency
{
    public virtual string Code { get; set; }

    public virtual decimal Rate { get; set; }

    public virtual IList<Country> Countries { get; set; }     
}

對於“國家/地區”實體,導航屬性DefaultCurrency的名稱與名稱“ Currency類型不同。 NHibernate的自動映射將猜測Country表將具有以下外鍵:

  • DefaultCurrency_id :對應於Country.Currency的關系

  • Currency_id :對應於Currency.Countries關系

如何告知自動映射可以使用DefaultCurrency_id鍵表示關系Currency.Countries ,從而導致僅對Country表使用外鍵:

  • DefaultCurrency_id :對應於Country.CurrencyCurrency.Countries的關系

您可以在映射中指定所需的任何列名稱。

供參考:

References(x => x.Foo, "MyFooId")

對於有很多:

HasMany(x => x.Foos)
    .KeyColumn("MyFooId")

對於多對多:

HasManyToMany(x => x.Foos)
    .ChildKeyColumn("MyFooId")
    .ParentKeyColumn("MyFooId")

您還可以使用約定,例如:

public class HasManyConventions : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance target)
    {
        target.Key.Column(target.EntityType.Name + "Id");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM