开发者

nhibernate mapping: delete collection, insert new collection with old IDs

开发者 https://www.devze.com 2022-12-25 10:11 出处:网络
my issue lokks similar to this one: (link) but i have one-to-many association: <set name=\"Fields\" cascade=\"all-delete-orphan\" lazy=\"false\" inverse=\"true\">

my issue lokks similar to this one: (link)

but i have one-to-many association:

<set name="Fields" cascade="all-delete-orphan" lazy="false" inverse="true">
  <key column="[TEMPLATE_ID]"></key>
  <one-to-many class="MyNamespace.Field, MyLibrary"/>
</set>

(i also tr开发者_如何学Cied to use ) this mapping is for Template object. this one and the Field object has their ID generators set to identity.

so when i call session.Update for the Template object it works fine, well, almost: if the Field object has an Id number, UPDATE sql request is called, if the Id is 0, the INSERT is performed. But if i delete a Field object from the collection it has no effect for the Database. I found that if i also call session.Delete for this Field object, everything will be ok, but due to client-server architecture i don't know what to delete.

so i decided to delete all the collection elements from the DB and call session.Update with a new collection. and i've got an issue: nhibernate performs the UPDATE operation for the Field objects that has non-zero Id, but they are removed from DB!

maybe i should use some other Id generator or smth.. what is the best way to make nhibernate perform "delete all"/"insert all" routine for the collection?


Is the entity you are updateing already associated with the session? (ie do you load the entity and modify that loaded instance)?

It sound like you are trying to tell nhibernate to update a detached entity, in this case nhiberante cannot know what entities as been added/removed in the collection. In this case you could use Merge:

var mergedEntity = session.Merge(entityPasedFromClient)

The merge operation will fetch the enity from the db compare it with the one that as been sent from the client and merge them, that way the entity that nhiberante fetch from the db (and is associated with the session) is modified and later fetched, the merged entity is returned (this will not be the same instance as the entity you pass the merge operation).

I am not sure I understand the last part of your question: "so i decided to delete all the collection elements from the DB and call session.Update with a new collection. and i've got an issue: nhibernate performs the UPDATE operation for the Field objects that has non-zero Id, but they are removed from DB!"

Are the field items updated and then removed?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号