c# - NHibernate cascade setting on child -
i try learn nhibernate first time. i'm using book: nhibernate2
there don't understand. on "contact.hbm.xml" mapping file there defined mapping orderheader table. orderheader table has 2 foreign keys contact table: "billtocontact_id" , "shiptocontact_id".
<bag name="billtoorderheaders" inverse="true" lazy="true" cascade="all-delete-orphan"> <key column="billtocontact_id"/> <one-to-many class="ordering.data.orderheader, ordering.data"/> </bag> <bag name="shiptoorderheaders" inverse="true" lazy="true" cascade="all-delete-orphan"> <key column="shiptocontact_id"/> <one-to-many class="ordering.data.orderheader, ordering.data"/> </bag>
in mapping have cascade="all-delete-orphan". aa understand, necessary set on primary table.
then mapping on orderheader table is:
<many-to-one name="billtocontact" class="ordering.data.contact, ordering.data"> <column name="billtocontact_id" not-null="false"/> </many-to-one> <many-to-one name="shiptocontact" class="ordering.data.contact, ordering.data"> <column name="shiptocontact_id" not-null="false"/> </many-to-one>
when try save new data:
isessionfactory sessionfactory = cfg.buildsessionfactory(); isession session = sessionfactory.opensession(); itransaction tx = session.begintransaction(); contact contact = new contact("joe", "jones", "joeyj@waywardone.com"); address address = new address("2000 e. captive way", null, "madville", "ma", "78701"); address.contact = contact; contact.addresses = new list<address>(); contact.addresses.add(address); orderheader header = new orderheader(); header.number = "0000001"; header.orderdate = datetime.now; header.billtocontact = contact; header.billtoaddress = address; header.shiptocontact = contact; header.shiptoaddress = address; session.saveorupdate(header); tx.commit();
i error: object references unsaved transient instance - save transient instance before flushing. type: ordering.data.contact, entity: ordering.data.contact
then have defined cascade inside child table mapping:
<many-to-one name="billtocontact" class="ordering.data.contact, ordering.data" cascade="all-delete-orphan"> <column name="billtocontact_id" not-null="false"/> </many-to-one> <many-to-one name="shiptocontact" class="ordering.data.contact, ordering.data" > <column name="shiptocontact_id" not-null="false"/> </many-to-one>
i don't understand this. if add cascade="all-delete-orphan" billtocontact mapping or shiptocontact mapping, works. doesn't matter, 1 of them must have setting.
as read if cascade define on parent, doesn't have defined on child. if must on child, logically on both mapping not on 1 of them(doesn't matter one).
can explain?
i guess problem of order. if tries store address first, there no cascade on address.contact
.
- either cascade insert-update
address.contact
, - or explicitly add contact before stored.
Comments
Post a Comment