Hello,
I have the following situation:
two tables, Child and Parent;
Child has PK column ChildId and FK column to Parent ParentId;
Parent has PK column ParentId.
.NET class Child has property Parent.
Sample code looks like this:
Configuration cfg = new Configuration();
cfg.AddAssembly( "SaveWithParent" );
ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = null;
try
{
// initialize tran
transaction = session.BeginTransaction();
// create new child
Child child = new Child();
child.Name = "Jonas Mazasis";
child.Parent = new Parent();
child.Parent.Name = "Jonas Didysis";
// tell NHibernate that this object should be saved
session.Save( child.Parent );
session.Save( child );
// commit all of the changes to the DB and close the ISession
transaction.Commit();
}
catch ( System.Exception exc )
{
if ( transaction != null )
{
transaction.Rollback();
}
}
finally
{
session.Close();
}
When I execute this code, I get the following insert statments:
NHibernate: select SEQ__TEST_PARENT.nextval from dual
NHibernate: select SEQ__TEST_CHILD.nextval from dual
NHibernate: INSERT INTO TEST_PARENT (NAME, PARENTID) VALUES (:p0, :p1); :p0 = 'Jonas Didysis', :p1 = '2'
NHibernate: INSERT INTO TEST_CHILD (PARENTID, NAME, PARENTID, CHILDID) VALUES (:p0, :p1, :p2, :p3); :p0 = '0', :p1 = 'Jonas Mazasis', :p2 = '2', :p3 = '4'
Parent is created with a first insert statement, then Child; notice, that Child creation statement has two PARENTID columns in it - first value is unspecified and second value is taken from newly inserted Parent. What I am doing wrong?
This code works when I set insert="False" in Child mapping file for property ParentId -- then first PARENTID value is removed from Child creation statement. But is this OK?
Regards,
Mindaugas
|