流利的NHibernate - 加入了子类ForeignKey Name

时间:2011-01-17 15:11:02

标签: nhibernate foreign-keys subclass fluent

我正在考虑转向Fluent NHibernate - 到目前为止我遇到的唯一问题是你不能在连接的子类映射上指定外键名称。

有没有人为此获得解决方案或解决方法?

我找到了this post,但明确的建议没有添加到代码中。

如果可能的话,我想避免自己定制代码。

任何帮助都会很棒......

示例:

public class Product
{
    public string Name { get; set; }
}

public class Hammer : Product
{
    public string Description { get; set; }
}

public class ProductMap : ClassMap<Product, long>
{
    public ProductMap()
    {
        Polymorphism.Implicit();
        Map(x => x.Name);
    }
}

public class HammerMap : SubclassMap<Hammer>
{
    public HammerMap()
    {
        Extends<Product>();
    }
}

这会生成如下内容:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="field.camelcase-underscore" auto-import="false" default-cascade="none" default-lazy="true">
  <class xmlns="urn:nhibernate-mapping-2.2" dynamic-insert="true" dynamic-update="true" mutable="true" polymorphism="implicit" optimistic-lock="version" name="Domain.Product, Domain" table="Product">
    <id name="Id" type="System.Int64">
      <column name="Id" />
      <generator class="native">
        <param name="sequence">ProductId</param>
      </generator>
    </id>
    <property name="Name" type="System.String">
        <column name="Name" />
    </property>
    <joined-subclass name="Domain.Hammer, Domain" table="Hammer">
      <key>
        <column name="Product_Id" />
      </key>
        <property name="Description" type="System.String">
          <column name="Description" />
        </property>
    </joined-subclass>
  </class>
</hibernate-mapping>

请注意,映射hbm文件中没有指定外键名称 - 如:

<joined-subclass name="Domain.Hammer, Domain" table="Hammer">
   <key column="Product_Id" foreign-key="FK_Hammer_Product"/>
</joined-subclass>

1 个答案:

答案 0 :(得分:5)

尝试这样的事情

public class JoinedSubclassForeignKeyConvention : IJoinedSubclassConvention
{
   public void Apply(IJoinedSubclassInstance instance)
   {
      instance.Key.ForeignKey(string.Format("FK_{0}_{1}", 
                    instance.EntityType.Name, instance.Type.Name));
   }
}