简体   繁体   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?

I'm using NHibernate/FluentNhibernate with AutoMapping configuration and I'm having troubles with foreign keys of some relationships. 我正在将NHibernate / FluentNhibernate与AutoMapping配置一起使用,但是在某些关系的外键上遇到了麻烦。 Especially those where the navigation property name is different from the the name of the type it is pointing to : 特别是那些导航属性名称与其指向的类型名称不同的属性:

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

In the case of Country entity where the name of navigation property DefaultCurrency is different from the name Currency type. 对于“国家/地区”实体,导航属性DefaultCurrency的名称与名称“ Currency类型不同。 The automapping of NHibernate will guess that the Country table will have the following foreign key: NHibernate的自动映射将猜测Country表将具有以下外键:

  • DefaultCurrency_id : corresponding to the relation of Country.Currency DefaultCurrency_id :对应于Country.Currency的关系

  • Currency_id : corresponding to the relation of Currency.Countries Currency_id :对应于Currency.Countries关系

How to tell to the automapping that the relation Currency.Countries can be expressed with DefaultCurrency_id key, resulting to one key foreign only for the Country table: 如何告知自动映射可以使用DefaultCurrency_id键表示关系Currency.Countries ,从而导致仅对Country表使用外键:

  • DefaultCurrency_id : corresponding to the relation of Country.Currency and Currency.Countries DefaultCurrency_id :对应于Country.CurrencyCurrency.Countries的关系

You can specify any column name you want in the mapping. 您可以在映射中指定所需的任何列名称。

For references: 供参考:

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

For has-many: 对于有很多:

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

For many-to-many: 对于多对多:

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

You can also use conventions, eg: 您还可以使用约定,例如:

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