开发者

NHibernate: mapping user type object to a separate table

Let's start with this mapping:

<component name="Location">
  ...
  <property name="Settings" type="JsonUserType,...">
    <column name="LocationSettingsType" />
    <column name="Locat开发者_运维百科ionSettingsData" />
  </property>
</component>

This maps to

TABLE Primary (
    ...
    LocationSettingsType,
    LocationSettingsData
    ...
)

and

class Location {
    ...
    object Settings { get; set; }
}

Now, I want to extract settings into a separate table (because they are seldom here).

So I get

TABLE Primary (
    ...
    LocationSettingsId,
    ...
)

TABLE Settings (
    Id,
    Type,
    Data
)

Can I keep my C# classes the same?

Update: This is not a many-to-one relationship. As before, each location has zero or one settings, and each settings belong to at most one location.


I believe the closest thing that exists to this is the <map> mapping element; details are explained in this article.


If you want a one to many relationship on the Primary and Settings tables, you'll have to set a foreign key constraint first. Then you'll use the bag property in XML to map your tables. You will have an entity for each table.

See also this question on NHibernate/FluentNHibernate Property Bag.

I also recommend you purchase the NHibernate 2 for Beginners book. It helped me alot.


This is an old question but i had the same issue and looking to a solution I came here.

the component element can map several columns to several object models.

the join element can map several tables to an object model.

The main problem is that while the component cannot map columns from a different table where the model belong, the join cannot map the different table columns to a different object model.

The solution I found is to use both to achieve the map column of a different table to several object:

<class name="Primary" table="Primary">
    <id name="Id">
        <generator class="identity"/>
    </id>
    <property name="Name" />
    ...
    <join table="Settings">
        <key column="PrimaryId"/>

        <component name="Location">
          ...
          <property name="Settings" type="JsonUserType,...">
            <column name="LocationSettingsType" />
            <column name="LocationSettingsData" />
          </property>
        </component>
    </join>
</class>

Reference:

NHibernate Join mapping element

NHibernate Component mapping element

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜