NHibernate - Why does Delete() call fail to delete but delete through HQL works?

只愿长相守 提交于 2019-12-04 21:43:33
Kent Boogaart

Try calling session.Flush() after you delete, but before you close the session. And you don't need to explicitly close the session:

using (var session = ...)
{
    entity.Delete();
    session.Flush();
}

After delving further into this, I found that this works but why?:

public static void Delete(Object Entity)
{
    using (ISession session = _sessionFactory.OpenSession())
    {       
         MyDAO p = session.Get<MyDAO>(Entity.ID);
         session.Delete(p);
         session.Flush();                                    
    }            
}

Here is my scenario: I have previously queried for a list of objects which I populated into a Grid. For that query process, I opened/closed a session. Upon calling my delete function, I take that object and pass it into this function for a separate open/close session process. To stir things up a bit, I added the call to this new delete asking it to get the object first (the one I want deleted), then call delete. Now it sends the delete query to the database and the object is in fact deleted. Why is this?

Is this because my original query of objects was opened within a different session and then deleted in another? Does this have anything to do with the unit of work. Should I open my session for my grid, leave it open until my form closes so all deletes work inside that session? I was under the impression that sessions should be opened/closed quickly. I'm confused.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!