我正在使用 NHibernate 3.3.2.4(不流畅)...我正在尝试将数据库模型映射到应用程序模型,但我遇到了困难。
我有以下数据库结构(为简洁起见):
LibraryItems
------------
Id UniqueIdentifier Primary Key,
UserId UniqueIdentifier Foreign Key References Users(UserId),
Type SmallInt,             --Book, Magazine etc.
ProductId UniqueIdentifier --Links to UserBooks When Type = 1
                           --         UserMagazines When Type = 2
UserBooks
---------
ProductId UniqueIdentifier Unique Foreign Key References Books(Id),
--Other fields pertaining to books
UserMagazines
-------------
ProductId UniqueIdentifier Unique Foreign Key References Magazines(Id),
--Other fields pertaining to magazines
UserBookmarks
-------------
Id UniqueIdentifier Primary Key,
LibraryItemId UniqueIdentifier Foreign Key References LibraryItems(Id),
BookmarkLocation NVarChar(100)
我也有以下应用模型
public enum LibraryItemType
{
    Book = 1,
    Magazine = 2
}
public abstract class LibraryItem
{
    public Guid Id { get; set; }   //ProductId
    public Guid UserId { get; set; }
    abstract public LibraryItemType Type { get; }
}
public abstract class ReadableLibraryItem : LibraryItem
{
    public Bookmark CurrentPosition { get; set; }
}
public class UserBook : ReadableLibraryItem
{
    public override LibraryItemType Type { get { return LibraryItemType.Book; } }
    //Other properties pertaining to books
}
public class UserMagazine : ReadableLibraryItem
{
    public override LibraryItemType Type { get { return LibraryItemType.Magazine; } }
    //Other properties pertaining to magazines
}
我完全不知道如何从我的数据库中的数据模型映射到应用程序模型......到目前为止我有:
<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping default-cascade="save-update" 
                   assembly="Model" 
                   namespace="Model.Library" 
                   default-lazy="false" xmlns="urn:nhibernate-mapping-2.2">
  <class name="LibraryItem" table="LibraryItems" optimistic-lock="version">
    <id name="Id" type="Guid" unsaved-value="00000000-0000-0000-0000-000000000000">
      <generator class="assigned"/>
    </id>
    <discriminator column="Type" type="Int32" />
    <property name="UserId" type="Guid" not-null="true" />
    <property name="ProductId" type="Guid" not-null="true" />
    <property name="Type" type="Model.Library.LibraryItemType, Model" not-null="true" />
    <joined-subclass name="ReadableLibraryItem">
      <one-to-one name="CurrentPosition" type="Model.Library.Bookmark" class="Bookmark" property-ref="LibraryItemId" />
      <joined-subclass name="UserBook" table="UserBooks" lazy="false" discriminator-value="1">
        <key column="Id" />
      </joined-subclass>
      <joined-subclass name="UserMagazineIssue" table="UserMagazineIssues" lazy="false" discriminator-value="2">
        <key column="Id" />
      </joined-subclass>
    </joined-subclass>
  </class>
</hibernate-mapping>
我的问题似乎有两个方面。
- 我的应用程序模型中的子类型 UserBooks 和 UserMagazines 实际上是 SubTypes 的子类型,我不知道如何在我的 hbm 文件中对其进行建模。
 - 鉴别器在 LibraryItems 表中,但在子子类中应用。