【问题标题】:How to do a NHibernate many-to-one/one-to-many foreign key in case of navigation property name different from property type?如果导航属性名称与属性类型不同,如何执行 NHibernate 多对一/一对多外键?
【发布时间】:2013-03-05 09:43:01
【问题描述】:

我正在使用 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的关系

如何告诉自动映射关系 Currency.Countries 可以用 DefaultCurrency_id 键表示,从而导致 Country 表只有一个键外:

  • DefaultCurrency_id:对应Country.CurrencyCurrency.Countries的关系

【问题讨论】:

  • 你能发布你的Fluent映射吗?

标签: c# .net nhibernate fluent-nhibernate


【解决方案1】:

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

供参考:

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

【讨论】:

    猜你喜欢
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    相关资源
    最近更新 更多