使用带有NHibernate.Mapping.Attributes的鉴别器为每个子类做表

时间:2010-06-29 11:21:20

标签: c# inheritance orm nhibernate-mapping hbm

我正在尝试使用NHibernate.Mapping.Attributes Table per subclass: using a discriminator。 hbm应如下所示:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <subclass name="SalesReport" discriminator-value="SalesReport" extends="Report">
    <join table="SalesReport">
      <key foreign-key="FK_SalesReport_Document" />
      <property name="TotalSales" />
      <property name="NetGrouth" />
    </join>
  </subclass>
</hibernate-mapping>

代码如下所示:

[Subclass(NameType=typeof(SalesReport),
    DiscriminatorValueObject=DocumentDiscriminator.SalesReport,
    ExtendsType=typeof(Report))]
[Serializable]
public partial class SalesReport : Common.Documents.Report
{
    [Join(Table = "SalesReport")]
    [Key(1, ForeignKey = "FK_SalesReport_Document")]
    [Property(2)]
    public virtual decimal TotalSales
    {
        get;
        set;
    }

    [Join(Table = "SalesReport")]
    [Key(1, ForeignKey = "FK_SalesReport_Document")]
    [Property(2)]
    public virtual decimal NetGrouth
    {
        get;
        set;
    }
}

结果是这样的:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <subclass name="SalesReport" discriminator-value="SalesReport" extends="Report">
    <join table="SalesReport">
      <key foreign-key="FK_SalesReport_Document" />
      <property name="TotalSales" />
    </join>
    <join table="SalesReport">
      <key foreign-key="FK_SalesReport_Document" />
      <property name="TotalSales" />
      <property name="NetGrouth" />
    </join>
  </subclass>
</hibernate-mapping>

它创建了正确的表结构(一个表有两个十进制字段,一个PF / FK到Reports表),但是在检测数据时它会失败,因为它会为每个字段生成两个插入:

NHibernate: INSERT INTO SalesReport (TotalSales, SalesReport) VALUES (@p0, @p1);@p0 = 13400,20, @p1 = 41
NHibernate: INSERT INTO SalesReport (NetGrouth, SalesReport) VALUES (@p0, @p1);@p0 = 0, @p1 = 41

有没有办法使用NHibernate.Mapping.Attributes完成这个?

1 个答案:

答案 0 :(得分:0)

您应该遵循XML版本来使用NHMA: 所以,如果你想要一个,只需加一个NHMA.Join,两个[Property(2&amp; 3,Name =“...”)]