开发者

NHibernate: cannot append items to map element

I have map element in my mapping -

 开发者_如何学编程       <component name="Resources">
        <map name="Inner" table="SomeTable" lazy="false" fetch="join" access="field.lowercase-underscore">
            <key column="Id"/>
            <index column="IndexId" type="String"/>
            <composite-element class="SomeResource">
                <property name="Name"/>
            </composite-element>
        </map>
        </component>

I want to append items in the SomeTable in the following way -

            var ent = new Entity();
        ent.Resources.Add("key1", new SomeResource());

        var saved = Session.SaveOrUpdate(ent);
        Session.Session.Flush();
        Session.Session.Clear();

        var newEntity = new Entity {Id = saved.Id};
        ent.Resources.Add("key2", new SomeResource());

        Session.SaveOrUpdate(newEntity);  // here nHib generates DELETE FROM SomeTable WHERE Id = saved.Id
        Session.Session.Flush();
        Session.Session.Clear();

I want to have elements "key1" & "key2" in the SomeTable after the run, how can this be done?.. Currently nHib deletes all elements with the specified id from the SomeTable before second save.


With this code you are creating two elements with the same id, that is a primary key: that's why NHibernate deletes the element "key1" (the ent object).

When you create newEntity, don't assing Id property (as you do with ent) if you want a completely new object. Otherwise, if you want to update an existing object, you do:

    var ent = new Entity();
    ent.Resources.Add("key1", new SomeResource());

    var saved = Session.SaveOrUpdate(ent);
    Session.Session.Flush();
    Session.Session.Clear();

    // later...

    var entToUpdate = Session.Get<Entity>(saved.Id);
    ent.Resources.Add("key2", new SomeResource());

    Session.SaveOrUpdate(entToUpdate);
    Session.Session.Flush();
    Session.Session.Clear();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜