Nhibernate 3 中的一对一映射

one-to-one mapping in Nhibernate 3

我有以下类

namespace Extractor.Mapping
{
    public class Application
    {
        public virtual Guid Id { get; set; }
        public virtual string intId { get; set; }
        virtual SQuery sQuery { get; set; }
    }
}


namespace Extractor.Mapping
{
    public class SQuery
    {
        public virtual int Id { get;set; } 
        public virtual Guid Application { get;set; } 
        public virtual string Type { get;set; }
    }
}

SQuery与Application的关系是SQuery中的外键"Application"

这些是 de hbm 文件

Application.hbm.xml

<hibernate-mapping  xmlns="urn:nhibernate-mapping-2.2"
                    assembly="Extractor"
                    namespace="Extractor.Mapping">

  <class name="Application" >
    <id name="Id" column="Id">
      <generator class="assigned"/>
    </id>
    <property name = "intId" column = "IntId" type = "string"/>
    <one-to-one name="sQuery" property-ref ="Application" class="SicQuery"/>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>

SQuery.hbm.xml

<hibernate-mapping  xmlns="urn:nhibernate-mapping-2.2"
                    assembly="BuroExtractorD"
                    namespace="BuroExtractorD.Mapping">
  <class name="SQuery" >
    <id name="Id" column="Id">
      <generator class="increment"/>
    </id>
    <property name="Application" column="Application" type ="Guid"/>
    <property name="Type" column="Type" type="string"/>
  </class>
</hibernate-mapping>

所以,事情是这样的,当我尝试访问一些 SQuery 对象的列表时,出现以下异常:

NHibernate.PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of Extractor.Mapping.SQuery ---> System.InvalidCastException

我尝试这样到达那里:

ICriteria crit = session.CreateCriteria(typeof(SQuery));
IList<SQuery> list = crit.List<SQuery>();

提前致谢

one-to-one的点是引用关系。这种映射不可能是关于ValueTypes.

public class Application
{
    public virtual SQuery sQuery { get; set; }
    ...
}
public class SQuery
{
    // wrong, Guid is ValueType, not a reference 
    // public virtual Guid Application { get;set; } 
    // corrrect - one to one == bi-directional 
    public virtual Application Application { get;set; } 
    ...
}

映射应该如下所示

<class name="Application" >
    ...
    // class should be SQuery
    //<one-to-one name="sQuery" property-ref ="Application" class="SicQuery"/>
    <one-to-one name="sQuery" property-ref="Application" class="SQuery"/>

 <class name="SQuery" >
    ...
    <many-to-one name="Application" class="Application" 
                 column="Application" unique="true"/>

在此处查看更多内容:

5.1.2. hibernate-mapping