Nhibernate : not-null property references a null or transient value error in many to one relationship

I am getting error not-null property references a null or transient value in many to one relation in NHibernate.

Code:

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;}
}

Mappings

<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

<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>

I am deleting records using below code.

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

If myDataCollection contains 2 instances which have same UploadData then I will get the error "not-null property references a null or transient value" on repo.Delete(obj)

I googled the issue and found solutions (e.g. make not-null="false" in mappings) but didn't solve the issue.

Answers


Specify cascade="all" then the delete operation is cascaded and NHibernate should take care of duplicate references.

<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);
}

I also see several problems here

  • public int UploadId{ get; set; } is redundant and will result in SQL parameter errors because the column is mapped twice. UploadData.UploadId will give the same
  • length="5" is ignored because it is only relevant for string columns

Need Your Help

Specify password hash instead of clear password in Oracle JDBC client

java oracle security jdbc

I'm using Oracle JDBC driver in my Java app to reach Oracle DB. Creating the connection using code:

Chisel Shiftregister Example

scala vhdl chisel

i'm very new with scala and Chisel. I tried to create a Shiftregister example with dynamic size, but i'm not sure if the following code is correct. It would be nice if someone could review it: