views:

53

answers:

1

Hi, I'm trying to make simple many-to-one association, using NHibernate.. I have class Recruit with this mapping:

<class name="Recruit" table="Recruits">
<id name="ID">
  <generator class="native"/>
</id>
<property name="Lastname" column="lastname"/>
<property name="Name" column="name"/>
<property name="MedicalReport" column="medicalReport"/>
<property name="DateOfBirth" column ="dateOfBirth" type="Date"/>
<many-to-one name="AssignedOnRecruitmentOffice"
   column="assignedOnRecruitmentOffice"
   class="RecruitmentOffice"/>

which is many-to-one connected to RecruitmentOffices:

<class name="RecruitmentOffice" table="RecruitmentOffices">
<id name="ID" column="ID">
  <generator class="native"/>
</id>
<property name="Chief" column="chief"/>
<property name="Name" column="name"/>
<property name ="Address" column="address"/>
<set name="Recruits" cascade="save-update" inverse="true" lazy="true">
  <key>
    <column name="AssignedOnRecruitmentOffice"/>
  </key>
  <one-to-many class="Recruit"/>
</set>

And create Repository class with method Insert:

 public void Insert(Recruit recruit)
    {
        using (ITransaction transaction = session.BeginTransaction())
        {
            session.Save(recruit);
            transaction.Commit();
        }
    }

then I try to save new recrui to base:

 Recruit test = new Recruit();
 RecruitmentOffice office = new RecruitmentOffice();
 ofice.Name = "test";
 office.Chief = "test";
 test.AssignedOnRecruitmentOffice = office;
 test.Name = "test";
 test.DateOfBirth = DateTime.Now;
 RecruitRepository testing = new RecruitRepository();
 testing.Insert(test);

And have this error

    GenericADOException 
could not insert: [OSiUBD.Models.DAO.Recruit][SQL: INSERT INTO Recruits (lastname, name, medicalReport, dateOfBirth, assignedOnRecruitmentOffice) VALUES (?, ?, ?, ?, ?); select SCOPE_IDENTITY()]

on session.Save

A: 

Looks like you need to make the Recruits table's [ID] column an identity column in your SQL schema.

Neil Moss
Thank you!!! I realy forgot to set identity to my primary key
Ris90
You're welcome.
Neil Moss