0

我正在自定义 N2CMS 的数据库结构,遇到了一个问题。下面列出了这两个类。

public class Customer : ContentItem
{
  public IList<License> Licenses { get; set; }
}

public class License : ContentItem
{
  public Customer Customer { get; set; }
}

nhibernate映射如下。

  <class name="N2.ContentItem,N2" table="n2item">
    <cache usage="read-write" />
    <id name="ID" column="ID" type="Int32" unsaved-value="0" access="property">
      <generator class="native" />
    </id>
    <discriminator column="Type" type="String" />
  </class>

  <subclass name="My.Customer,My" extends="N2.ContentItem,N2" discriminator-value="Customer">
    <join table="Customer">
      <key column="ItemID" />
      <bag name="Licenses" generic="true" inverse="true">
        <key column="CustomerID" />
        <one-to-many class="My.License,My"/>
      </bag>
    </join>
  </subclass>

  <subclass name="My.License,My" extends="N2.ContentItem,N2" discriminator-value="License">
    <join table="License" fetch="select">
      <key column="ItemID" />
      <many-to-one name="Customer" column="CustomerID"  class="My.Customer,My" not-null="false" />
    </join>
  </subclass>

然后,当获取客户实例时,customer.Licenses 始终为空,但实际上数据库中有客户的许可证。当我检查 nhibernate 日志文件时,我发现 SQL 查询是这样的:

SELECT   licenses0_.CustomerID     as CustomerID1_,
         licenses0_.ID             as ID1_,
         licenses0_.ID             as ID2_0_,
         licenses0_1_.CustomerID   as CustomerID7_0_,
FROM     n2item licenses0_
         inner join License licenses0_1_
           on licenses0_.ID = licenses0_1_.ItemID
WHERE    licenses0_.CustomerID = 12 /* @p0 */

似乎 nhibernate 认为 CustomerID 在“n2item”表中。我不知道为什么,但为了让它工作,我认为 SQL 应该是这样的。

SELECT   licenses0_.ID             as ID1_,
         licenses0_.ID             as ID2_0_,
         licenses0_1_.CustomerID   as CustomerID7_0_,
FROM     n2item licenses0_
         inner join License licenses0_1_
           on licenses0_.ID = licenses0_1_.ItemID
WHERE    licenses0_1_.CustomerID = 12 /* @p0 */

有人能指出我的映射有什么问题吗?我怎样才能获得一位客户的正确许可证?提前致谢。

4

1 回答 1

0

我不确定 SQL 是否不正确,因为父类映射使用了鉴别器,所以我希望所有属性都存储在与基类 (n2item) 相同的表中。但是我不熟悉“join table”语法,我通常使用joined-subclass,所以我可能会误解。

假设子类映射是正确的,许可证问题是否与没有为该集合设置级联设置有关?

于 2010-04-09T14:57:40.757 回答