c# - Why one-to-many does not work as expected in NHibernate? -
i have simple situation , don't have clue why isn't working.
this schema:
**[item]** id (pk) symbol **[item_version]** id (pk) item_id (fk->item) symbol
these mappings:
item.hbm.xml
<class name="core.model.entities.item, core.model" table="item" lazy="false"> <id name="id" column="id" type="long"> <generator class="native" /> </id> <property name="symbol" column="symbol"/> <bag name="itemversions" lazy="false" table="item_version" inverse="true" cascade="save-update"> <key column="item_id" /> <one-to-many class="core.model.entities.itemversion, core.model"/> </bag> </class>
*item_version.hbm.xml*
<class name="core.model.entities.itemversion, core.model" table="item_version" lazy="false"> <id name="id" column="id" type="long"> <generator class="native" /> </id> <many-to-one name="item" class="core.model.entities.item, core.model" column="item_id" cascade="save-update"/> <property name="symbol" column="symbol"/> </class>
these classes:
item.cs
public class item : entity<iitemdao> { private long id; virtual public long id { { return this.id; } set { this.id = value; } } private string symbol; virtual public string symbol { { return this.symbol; } set { this.symbol = value; } } private ilist<itemversion> item_versions = new list<itemversion>(); virtual public ilist<itemversion> itemversions { { return this.item_versions; } set { this.item_versions = value; } } }
itemversion.cs
public class itemversion : entity<iitemversiondao> { private long id; virtual public long id { { return this.id; } set { this.id = value; } } private item item = null; virtual public item item { { return this.item; } set { this.item = value; } } private long item_id = 0; virtual public long itemid { { return this.item_id; } set { this.item_id = value; } } private string symbol; virtual public string symbol { { return this.symbol; } set { this.symbol = value; } } }
and code...
item item = new item(); item.name = "test"; itemversion v = new itemversion(); v.symbol = "test version"; item.itemversions.add(v); item.dao.save(tmp);
... not work. inserts item , throws exception while inserting item_version row, item_version.item_id cannot null. item_id property isn't automatically set nhibernate in itemversion object. why cascade="save-update" , inverse="true" not work in case?
when set manually, adding code:
v.item = item;
and call save, works fine, not except nhibernate - calling
item.itemversions.add(v);
should sufficient.
am doing wrong or imposible? in advance answers :)
you have set v.item because itemversions inverse
. means "other side" (the many-to-one) in charge of maintaining relationship.
this standard practice; make easier use add method item:
public void additemversion(itemversion itemversion) { itemversions.add(itemversion); itemversion.item = this; }
Comments
Post a Comment