title: "not-null property references a null or transient value" when deleting entity using NHibernate
body: <p>I'm writing a simple application to learn new technologies. I'm stuck at writing unit test for my application:</p>
  
  <pre><code>    [Test]
      public void LessonChangeSubjectShouldNotAffectFormerSubjectPersistence()
      {
          // given
          Lesson ExampleLesson = TestDataFactory.CreateLesson();
          Save(ExampleLesson);
          Refresh(ref ExampleLesson);
          Subject formerSubject = ExampleLesson.Subject;
  
          // when
          Subject subject = TestDataFactory.CreateSubject();
          _subjectService.Save(subject);
          ExampleLesson.ChangeSubject(subject);
          Update(ExampleLesson);
          _subjectService.Update(formerSubject);
          Refresh(ref ExampleLesson);
          formerSubject = _subjectService.Get(formerSubject.Id);
          subject = _subjectService.Get(subject.Id);
  
          // then
          ExampleLesson.Subject.Should().Be(subject);
          formerSubject.Should().NotBeNull();
          formerSubject.Lessons.Should().NotContain(ExampleLesson);
  
          Refresh(ref ExampleLesson);
  
          _subjectService.Delete(formerSubject);
          Refresh(ref ExampleLesson);
          Delete(ExampleLesson);
      }
  </code></pre>
  
  <p>This scenario includes:</p>
  
  <ol>
  <li>Creating lesson with default random subject and save it</li>
  <li>Create new subject and change lesson subject to new one</li>
  <li>Check whether old subject still exists</li>
  </ol>
  
  <p>This scenario succeeds, but when it comes to cleaning up test fails on the last line with error </p>
  
  <blockquote>
    <p>NHibernate.PropertyValueException : not-null property references a null or transient value Register.Core.Model.Lesson.Subject</p>
  </blockquote>
  
  <p>Subject field in Lesson class is mapped as follows:</p>
  
  <pre><code>References(x =&gt; x.Subject)
  .Cascade.SaveUpdate()
  .Column("SubjectId")
  .Fetch.Select()
  .ForeignKey("FK_Lessons_Subjects")
  .Index("IX_Subject")
  .LazyLoad()
  .Not.Nullable();
  </code></pre>
  
  <p>And Lessons collection in Subject class is mapped as:</p>
  
  <pre><code>HasMany(x =&gt; x.Lessons)
  .Access.CamelCaseField(Prefix.Underscore)
  .Cascade.All()
  .Fetch.Select()
  .ForeignKeyConstraintName("FK_Lessons_Subjects")
  .Inverse()
  .KeyColumn("SubjectId")
  .Not.KeyNullable()
  .LazyLoad();
  </code></pre>
  
  <p>When I swap </p>
  
  <pre><code>    _subjectService.Delete(formerSubject);
  </code></pre>
  
  <p>with</p>
  
  <pre><code>    Refresh(ref ExampleLesson);
      Delete(ExampleLesson);
  </code></pre>
  
  <p>there's no complaint from NHibernate and test passes. I'm curious what's going on and why does the order matter. I also would be very grateful if someone could point me to solution for my problem. Thank you in advance.</p>