一个继承关系类型通过NHibernate进行映射的案例

以下内容译自我发往NHibernate国际用户组的邮件。

look at the summary of type definition
首先来看类型定义的摘要:

public abstract class Person
{
        public abstract Guid PersonID
        {
            get;
            set;
        }

        public abstract string FirstName
        {
            get;
            set;
        }

        public abstract string LastName
        {
            get;
            set;
        }
}

public class Customer:Person
{
   
    #region override some properties of Person here
        #endregion

    public Guid CustomerID
    {
        get;
        set;
    }

    public String Email
    {
       get;
       set;
    }

    public ISet<Store> Stores
    {
       get;
       set;
    }
}

public class Store
{
    public Guid StoreID
    {
           get;
       set;
    }

    public String Name
    {
       get;
       set;
    }

    public Customer Owner
    {
      get;
          set;
    }
}

Now, we do the mapping
现在来看映射的实现:

The Person with Customer:
含有子类Customer的Person类:
<class name="DAL.Model.Person, DataAccessLayer" table="Person" abstract="true" >
<id name="PersonID" column="PersonID" type="Guid"  length="36" >
   <generator class="guid" />
</id>
<property name="FirstName" column="FistName" type="String" length="100" />
<property name="LastName" column="LastName" type="String" length="100" />

  <!-- Customer-->
  <joined-subclass table ="Customer" name="DAL.Model.Customer, DataAccessLayer" >
    <key column="PersonID"/>
    <property name="CustomerID" column="CustomerID" type="Guid" length="36" update="false"/>
    <property name="Email" column="Email" type="String" length="100" />

    <!--  
    note: As the Customer type inherited from the Person type
    注意:如上所示,Customer类型继承自Person类型
     when you insert a new Store in DB, The Person's ID value will inserted into the Store table OwnerID column.

     当你在数据库中插入新的Store数据时,Person类型的主键值将会插入到Store表的外键列OwnerID中。
     so Store table foreign key constraint's primary key must be the Person's ID column.
      所以,Store表的外键约束的主键必须是Person表的主键列。
     If the Store table foreign key constraint's primary key set to Customer's primary key column, NH will be unable to properly handle this mapping.

     如果Store表的外键约束的主键设为Customer类型的主键列,NHibernate将无法正确处理这种映射。
    -->
    <set name="Stores" table="Store" generic="true"  cascade="all-delete-orphan"  >
      <key column="OwnerID" foreign-key="FK_Store_Person"   />
      <one-to-many class="DAL.Model.Store, DataAccessLayer" />
    </set>
  </joined-subclass>
 
</class>

The Store
Store类型:
<class name="DAL.Model.Store, DataAccessLayer" table="Store">
    <id name="StoreID" column="StoreID" type="Guid"  length="36" >
      <generator class="guid" />
    </id>
       
    <many-to-one name="Owner" class="DAL.Model.Customer" column="OwnerID" />   
    <property name="Name" column="Name" type="String" length="100" />
   
</class>

posted @ 2009-09-09 16:09  江名峰  阅读(591)  评论(0编辑  收藏  举报