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。我不知道什麼是錯的。
你可以添加你的類到這個問題嗎? –
在保存之前,你是否檢查過'Question'和'Test'對象是否有正確的引用? –
@DavidOsborne你是什麼意思?我將粘貼它 編輯:已過期 – Karolina