【问题标题】:not-null property references a null or transient value非空属性引用空值或瞬态值
【发布时间】:2017-04-25 01:16:45
【问题描述】:

我正在使用 NHibernate,但遇到了问题,因为尝试保存到数据库时会引发异常:

非空属性引用空值或瞬态值 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。我不知道可能出了什么问题。

【问题讨论】:

  • 您可以将您的课程添加到问题中吗?
  • 在保存QuestionTest 对象之前,您是否检查过它们之间的引用是否正确?
  • @DavidOsborne 你是什么意思?我会粘贴它编辑:已粘贴
  • 粘贴实际 QuestionTest 类的代码。看看他们如何相互引用会很好。
  • @DavidOsborne 完成,但代码没有粘贴最好的。不知道为什么stackoverflow这样编辑它

标签: c# nhibernate


【解决方案1】:

确保questionEntityTest 属性设置为映射为Not.Nullable()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-23
    • 2010-10-08
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多