2016-12-09 69 views
0

我使用NHibernate和我有一個問題,因爲試圖保存到數據庫時,它拋出一個異常:非空屬性引用null或瞬時值

非空屬性引用空或瞬時值NHibernate.Entities.Question.Test

我怎樣才能改變呢?

public class TestMap: ClassMap<Test> 
{ 
    public TestMap() 
    { 
     Table("Test"); 

     Id(x => x.Id) 
      .GeneratedBy.Identity() 
      .Column("Id"); 

     Map(x => x.Name) 
      .Column("Name") 
      .Not.Nullable(); 

     HasMany(x => x.Question).KeyColumn("TestId") 
     .Cascade.All() 
     .Not.LazyLoad(); 
    } 
} 

public class QuestionMap: ClassMap<Question> 
{ 
    public QuestionMap() 
    { 
     Table("Question"); 

     References(x => x.Test) 
      .Column("TestId") 
      .Not.Nullable() 
      .Cascade.SaveUpdate() 
      .Not.LazyLoad(); 

     Id(x => x.Id) 
      .GeneratedBy.Identity() 
      .Column("Id"); 

     Map(x => x.QuestionContent) 
      .Column("QuestionContent") 
      .Not.Nullable(); 

     HasMany(x => x.Answer) 
      .KeyColumn("QuestionId") 
      .Cascade.All() 
     //.Cascade.SaveUpdate() 
     .Not.LazyLoad(); 
    } 
} 

編輯:類

public class Question: Entity 
{ 
    public Question() 
    { 
     Answer = new List<Answer>(); 
    } 
    public virtual string QuestionContent { get; set; } 
    public virtual IList<Answer> Answer { get; set; } 
    public virtual Test Test { get; set; } 

    public virtual void AddAnswer(Answer answer) 
    { 
     answer.Question = this; 
     Answer.Add(answer); 
    } 
} 

public class Test : Entity 
{ 
    public Test() 
    { 
     Question = new List<Question>(); 
    } 

    public virtual string Name { get; set; } 
    public virtual IList<Question> Question { get; set; } 

    public virtual void AddQuestion(List<Question> questions) 
    { 
     foreach (var question in questions) 
     { 
      question.Test = this; 
      Question.Add(question); 
     } 
    } 
} 

問題有答案,答案有GivenAnswer和GivenAnswer有SolvedTest。我不知道什麼是錯的。

+0

你可以添加你的類到這個問題嗎? –

+0

在保存之前,你是否檢查過'Question'和'Test'對象是否有正確的引用? –

+0

@DavidOsborne你是什麼意思?我將粘貼它 編輯:已過期 – Karolina

回答

-1

確保questionEntity已將其Test屬性設置爲它的映射爲Not.Nullable()

相關問題