我使用NHibernate并且遇到了问题,因为在尝试保存到数据库时它会引发异常:
not-null属性引用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有SolvedTest。我不知道会出现什么问题。
答案 0 :(得分:-1)
确保questionEntity
设置了Test
属性,因为它已映射为Not.Nullable()
。