0

I'm using NHibernate and I have a problem, because when trying to save to a database it throws an exception:

not-null property references a null or transient value NHibernate.Entities.Question.Test

How can I change it?

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();
    }
}

EDIT: class

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);
        }
    }
}

Question has Answer, Answer has GivenAnswer and GivenAnswer has SolvedTest. I have no idea what could be wrong.

slavoo
  • 5,798
  • 64
  • 37
  • 39
Karolina
  • 41
  • 8

1 Answers1

-2

Ensure that questionEntity has its Test property set as it's mapped as Not.Nullable().

David Osborne
  • 6,436
  • 1
  • 21
  • 35