Pre Exam Test Practice (SSC | Banking | IAS | GATE | State Level | CLAT | Railways | Insurance | Teaching Exams | NDA | Defence | IES |State Exam )

Organizational Research By

Surprising Reserch Topic

fluent nhibernate cascade issue trying to insert null id using -'.net,,nhibernate,fluent-nhibernate'

fluent nhibernate cascade issue trying to insert null id  using -'.net,,nhibernate,fluent-nhibernate'

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)
    Map(x => x.Title);
    Map(x => x.Description);
    HasMany(x => x.CompetitionAnswers)

CompetitionAnswerMap (Fluent NHibernate Mapping)

public CompetitionAnswerMap()
    Id(x => x.CompetitionAnswerId)
    Map(x => x.Answer);
    References(x => x.Competition)

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



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?

asked Sep 7, 2015 by rajesh
0 votes

Related Hot Questions

Government Jobs Opening