How can I change my NHibernate mapping involving a composite id to execute
the expected sql statement?
I'm using FluentNHibernate and building a system where a Customer object
exposes several CustomerProperty objects, basically a per-customer
key-value store.
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);
}
}
This works and generates proper NHibernate mappings. I've exported them
using the built-in capabilities of 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>
This mapping, however, generates a sql query that does not visually please
me. (I can be pretty pedantic.) NHibernate Profiles shows me that the
following query executes.
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 */
There are duplicate references to the CustomerId and the Key column. How
can I remove these and only return a result of three columns (CustomerId,
Key, Value)?
No comments:
Post a Comment