Nhibernate:not-null属性在多对一关系中引用null或transient值错误

时间:2012-06-11 11:36:43

标签: c# nhibernate nhibernate-mapping spring.net

我在NHibernate中的多对一关系中收到错误 not-null属性引用空值或瞬态值

代码:

class MyData
{
    public string Name{get;set;}    
    public virtual UploadData UploadData { get; set; }
    public int UploadId{get;set;}
}

class UploadData
{
    public int UploadId{get;set;}
    public DateTime Date{get;set;}
}

映射

<class name="MyData, NS" table="MyData" lazy="false">
    <id name="Identifier" type="Int32" unsaved-value="0">
      <column name="Identifier" sql-type="int" 
              not-null="true" unique="true" index="PK_dbo.MyData"/>
      <generator class="identity" />
    </id>
    <property name='Name' column='Name'/>
    <property name='UploadId' column='UploadId'/>      
    <many-to-one name="UploadData" class="UploadData, NS">
          <column name="UploadId" length="5" sql-type="int" not-null="true" index="UploadId"/>
    </many-to-one>
 </class>

UploadData类

<class name="UploadData, NS" table="UploadData" lazy="false">
    <id name="UploadId" type="Int32" unsaved-value="0">
      <column name="UploadId" sql-type="int" 
              not-null="true" unique="true" index="PK_dbo.UploadData"/>
      <generator class="identity" />
    </id>
    <property name='Data' column='Date' />
</class>

我正在使用以下代码删除记录。

foreach(MyData obj in myDataCollection)
repo.Delete(obj) // delete using repository.
repo.Delete(obj.UploadData) 

如果myDataCollection包含2个具有相同UploadData的实例,那么我将在repo.Delete(obj)上获得错误“not-null属性引用空值或瞬态值”

我用Google搜索了问题并找到了解决方案(例如,在映射中make not null =“false”),但没有解决问题。

1 个答案:

答案 0 :(得分:1)

指定cascade="all"然后级联删除操作,NHibernate应该处理重复的引用。

<many-to-one name="UploadData" class="UploadData, NS" cascade="all">

// then this is enough to delete mydata and associated UploadData
foreach(MyData obj in myDataCollection)
{
   repo.Delete(obj);
}

我在这里也看到了几个问题

  • public int UploadId{ get; set; }是多余的,会导致SQL参数错误,因为列会映射两次。 UploadData.UploadId将提供相同的
  • length="5"被忽略,因为它仅与字符串列相关