nhibernate - Insert to parent and child tables -


hi have parent , child table below

<?xml version="1.0" encoding="utf-8"?>                      ------- parent -------------- <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">   <class name="hibernatesample.studmarks,hibernatesample" table="studmarks" lazy="false">     <id name="sno" column="sno" type="int">       <generator class="assigned"/>     </id>     <many-to-one name="student" column="id" not-null="true"/>     <property name="marks" column="marks" type="int" not-null="true" />     <property name="rank" column="rank" type="int" not-null="true" />   </class> </hibernate-mapping>                 ------- child -------------- <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">   <class name="hibernatesample.student,hibernatesample" table="student" lazy="false">     <id name="id" column="id" type="int">       <generator class="native" />     </id>     <property name="name" column="name" type="string" not-null="true" />     <property name="standard" column="standard" type="string" not-null="true" />     <bag name="studmarks" cascade="all" lazy="false">       <key column="id" not-null="true"/>       <one-to-many class="hibernatesample.studmarks,hibernatesample" />     </bag>   </class> </hibernate-mapping> 

and in .cs file have written code below insert parent , child.

        studmarks sm = new studmarks();          student st = new student();         list<studmarks> sms = new list<studmarks>();         st.id = 9;         st.name = "stud 999";         st.standard = "99";         sm.sno = 9;         sm.marks = 99;         sm.rank = 9;                      sm.student = st;              ------ **line 1**         st.studmarks = sms;           ------ **line 2**          session.save(sm);                     session.flush(); 

if comment "line 1" in above code child inserting. if comment "line 2" foreign key constraint error throwing.

tables:

create table [dbo].[student]( [id] [int] identity(1,1) not null, -- primary key [name] [varchar](50) not null, [standard] [varchar](50) not null,  create table [dbo].[studmarks]( [sno] [int] not null, -- primary key [id] [int] not null, -- foreign key [marks] [int] not null, [rank] [int] not null,) 

please let me know how insert in parent , child @ time in single save operation.

you have cascade relation student->studentmarks. should saving st...

session.save(st); 

you should specify inverse="true" on bag don't double updates of foreign key , cascade="all-delete-orphan" appropriate here want studentmarks deleted when student deleted.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -