I have the following models & mappings (code snippets further below).
One Competition has to have multiple CompetitionAnswers associated with it (multiple choice) from the outset.
At present, using the Fluent NHibernate mappings shown below, when I create a brand new Competition object, populate the properties, then create 3 brand new CompetitionAnswer objects and add them to the CompetitionAnswers property (property on Competition), I would expect to call Save on the session which would INSERT the 1 Competition row and 3 CompetitionAnswer rows to the DB.
However, as soon as I try to call Save on the session, it complains that CompetitionId is null and it can't insert a null into the CompetitionAnswers table for that field - which is right, it shouldn't, however, I assumed that the NHibernate would first create the Competition, then use the newly generated IDENTITY value (CompetitionId) in the CompetitionAnswers table?
Competition (Model)
public virtual int CompetitionId { get; private set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual IList<CompetitionAnswer> CompetitionAnswers { get; set; }
CompetitionAnswer (Model)
public virtual int CompetitionAnswerId { get; set; }
public virtual string Answer { get; set; }
public virtual Competition Competition { get; set; }
CompetitionMap (Fluent NHibernate Mapping)
public CompetitionMap()
{
Id(x => x.CompetitionId)
.GeneratedBy.Native();
Map(x => x.Title);
Map(x => x.Description);
HasMany(x => x.CompetitionAnswers)
.Cascade.AllDeleteOrphan()
.KeyColumn("CompetitionId")
.Inverse();
Table("Competitions");
}
CompetitionAnswerMap (Fluent NHibernate Mapping)
public CompetitionAnswerMap()
{
Id(x => x.CompetitionAnswerId)
.GeneratedBy.Native();
Map(x => x.Answer);
References(x => x.Competition)
.Column("CompetitionId");
Table("CompetitionAnswers");
}
Here is some sample code that I've used to test this scenario, which generates the error:
Competition c = new Competition();
c.Description = "Description";
c.Title = "Title";
CompetitionAnswer a1 = new CompetitionAnswer { Answer = "Answer 1" };
CompetitionAnswer a2 = new CompetitionAnswer { Answer = "Answer 2" };
CompetitionAnswer a3 = new CompetitionAnswer { Answer = "Answer 3" };
c.CompetitionAnswers.Add(a1);
c.CompetitionAnswers.Add(a2);
c.CompetitionAnswers.Add(a3);
session.Save(c);
The exact error that I get as soon as it tries to Save is:
Cannot insert the value NULL into column 'CompetitionId', table 'CompetitionAnswers'; column does not allow nulls. INSERT fails. The statement has been terminated.
Can anyone please shed any light on why this isn't currently working?