deleting and creating new child collection in Nhibernate in same session

I have a requirement to delete an existing collection inside a parent item and insert new collection entries. This should happen in same transaction. Kindly check the below hbm config. Please let me know why the delete is not happening with below code.

<class name="Category" table="Category" schema="dbo" lazy="true">
<id name="ID" access="property" column="Category_ID" unsaved-value="0">
  <generator class="native">
  </generator>
</id>

<property name ="CategoryName" access="property" column="Category_Name" not-null="true"/>
<bag name="Ratios" access="property"  table="Ratio" inverse="true" cascade="all"  lazy="true">
  <key column="CategoryID" />
  <one-to-many class="Category, Domain" />
</bag>

C# code:

if (ratios!= null && ratios.Count > 0)
                            {
                                ratios= ratios.Where(a => a.ID == 0).ToList<Ratio>();
                                cat.Ratios = ratios;
                                if (cat.ID == 0)
                                {
                                    _repository.Save(cat);
                                }
                                else
                                {
                                    _repository.Update(cat);
                                }
                            }

Please note that this is within a single Nhibernate session transaction. I am only passing the new collection using ratios= ratios.Where(a => a.ID == 0).ToList(); So the collection now doesnt have already saved entities in the reference.


You'll probably need to manually clear the collection and add all of the new ratios back to the collection. I'm positive you can't just set the collection to a new reference like you are doing above. There is no way that NHibernate can track the changes to the collection when you do that.

I have not tested the below but it should be closer to what you need:

cat.Ratios.Clear();
foreach(Ration ratio in ratios)
    cat.Ratios.Add(ratio);

Also what exactly are _repository.Save(cat) and _repository.Update(cat) doing? If they are calling ISession.Save and ISession.Update this is unnecessary since you probably have cascading set up on your one-to-many collection Ratios . You can simply commit your transaction as NHibernate tracks changes to entities/collections via the ISession

链接地址: http://www.djcxy.com/p/23244.html

上一篇: 我们如何使用startActivityforResult()作为电子邮件意图?

下一篇: 在同一会话中删除并在Nhibernate中创建新的儿童收藏