【问题标题】:How can I change my NHibernate mapping involving a composite id to execute the expected sql statement?如何更改涉及复合 id 的 NHibernate 映射以执行预期的 sql 语句?
【发布时间】:2013-09-19 15:30:31
【问题描述】:

我正在使用 FluentNHibernate 并构建一个系统,其中 Customer 对象公开多个 CustomerProperty 对象,基本上是每个客户的键值存储。

public class CustomerMap : ClassMap<Customer> {
    public CustomerMap() {
        Table("Customer");
        Id(x => x.Id);

        Map(x => x.UserName);
        HasMany(x => x.Properties);
    }
}

public class CustomerPropertyMap : ClassMap<CustomerProperty> {
    public CustomerPropertyMap() {
        Table("CustomerProperty");
        CompositeId()
            .KeyReference(x => x.Customer, MapData<Customer>.KeyColumn)
            .KeyProperty(x => x.Key);

        Map(x => x.Value);
    }
}

这可以工作并生成正确的 NHibernate 映射。我已经使用 FluentNHibernate 的内置功能导出了它们。

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class xmlns="urn:nhibernate-mapping-2.2" dynamic-update="true" name="Bazinga.Domain.CustomerProperty, Bazinga.Domain, Version=0.0.0.0, Culture=neutral, PublicKeyToken=108b91ac50cc98b9" table="CustomerProperty">
        <composite-id>
            <key-many-to-one name="Customer" class="Bazinga.Domain.Customer, Bazinga.Domain, Version=0.0.0.0, Culture=neutral, PublicKeyToken=108b91ac50cc98b9">
                <column name="CustomerId" />
            </key-many-to-one>
            <key-property name="Key" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                <column name="Key" />
            </key-property>
        </composite-id>
        <property name="Value" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <column name="Value" />
        </property>
    </class>
</hibernate-mapping>

然而,这个映射生成的 sql 查询在视觉上并不让我满意。 (我可能很迂腐。)NHibernate Profiles 告诉我执行了以下查询。

SELECT properties0_.CustomerId as CustomerId1_,
       properties0_.[Key]      as Key2_1_,
       properties0_.CustomerId as CustomerId13_0_,
       properties0_.[Key]      as Key2_13_0_,
       properties0_.[Value]    as Value3_13_0_
FROM   CustomerProperty properties0_
WHERE  properties0_.CustomerId = 1337 /* @p0 */

CustomerIdKey 列的引用重复。如何删除这些并只返回三列的结果(CustomerIdKeyValue)?

【问题讨论】:

    标签: hibernate nhibernate fluent-nhibernate nhibernate-mapping hibernate-mapping


    【解决方案1】:

    您是否尝试过使用 .KeyProperty 而不是 .KeyReference 的两个 CompositeId 字段?

    【讨论】:

    • .KeyProperty 用于基本类型,而 .KeyReference 用于引用。在这种情况下,Customer 属性是对另一个域类型的引用。使用 KeyProperty 会让事情变得一团糟,映射的属性变成“Id”(来自 Customer.Id),抛出异常,一切都不顺利。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2013-04-04
    • 1970-01-01
    • 2021-09-30
    • 2019-11-10
    • 2011-04-29
    相关资源
    最近更新 更多