Primary key as foreign key in NHibernate Association

380 views
Skip to first unread message

Ahmed Emad

unread,
Jul 13, 2009, 7:46:06 AM7/13/09
to nhusers
hi

i have atable which has 2 many-to-one relations with another 2 tables

where the Pks for this table are the foreign key of the other 2
tables

this is the mapping :

<class name="Project" table="Project" lazy="false" >
<id name="ProjectId" column="ProjectId" type="Int32">
<generator class="native"/>
</id>
<set name="Assignments" lazy="true" inverse="true" cascade="save-
update" >
<key>
<column name="ProjectId"/>
</key>
<one-to-many class="Assignment"/>
</set>
</class>

==========================================================
<class name="Resource" table="Resource" lazy="false" >
<id name="ResourceId" column="ResourceId" type="Int32">
<generator class="native"/>
</id>
<set name="Assignments" lazy="true" inverse="true" cascade="save-
update" >
<key>
<column name="ResourceId"/>
</key>
<one-to-many class="Assignment"/>
</set>
</class>

===================================================================

and there the class where the problem appear :

<class name="Assignment" table="Assignment" lazy="false" >
<composite-id name="AssignmentId" class="AssignmentId" >
<key-property name="ProjectId" column="ProjectId" type="Int32" />
<key-property name="ResourceId" column="ResourceId" type="Int32" />
</composite-id >

</class>


i get this error :

could not insert: [ManyTest.Entities.Assignment][SQL: INSERT INTO
Assignment (ProjectId, ResourceId) VALUES (?, ?)]

{"The INSERT statement conflicted with the FOREIGN KEY constraint
\"Project_Assignment\". The conflict occurred in database \"Many\",
table \"dbo.Project\", column 'ProjectId'.\r\nThe statement has been
terminated."}


any help?


Eyston

unread,
Jul 13, 2009, 2:39:02 PM7/13/09
to nhusers
What is the code look like for creating/saving the entities? It looks
like Assignment is being saved with a ProjectID that does not
reference any record in dbo.Project (which is SQL Server complaining,
not NHibernate ... I think!).

Stefan Steinegger

unread,
Jul 13, 2009, 3:03:08 PM7/13/09
to nhusers
Is there a reason why you don't use a many-to-many relation? I assume
there are additional properties in the assignment class?

You should probably use the <key-many-to-one> element instead of the
<key-property> element, to tell NH that this id is actually many-to-
one relation. i never used this, just looking up the documentation.
Reply all
Reply to author
Forward
0 new messages