How to delete an object by using PK in nhibernate?

后端 未结 5 1222

How do I delete an object without fetching it from the db first?

In another ORM, I can do this:

session.Delete(1); // 1 = PK
相关标签:
5条回答
  • 2021-02-02 17:08

    Check out the ExecuteUpdate method on the IQuery object.

    IQuery q = session.CreateQuery ("delete from User where Id = 1");
    q.ExecuteUpdate();
    

    Should delete the object without retrieving it afaik.

    0 讨论(0)
  • 2021-02-02 17:09

    Add the following class to your project:

    public static class SessionHelper
    {
        public static void Delete<TEntity>(this ISession session, object id)
        {
            var queryString = string.Format("delete {0} where id = :id",
                                            typeof(TEntity));
            session.CreateQuery(queryString)
                   .SetParameter("id", id)
                   .ExecuteUpdate();
        }
    }
    

    You can now use session.Delete<User>(1).

    0 讨论(0)
  • 2021-02-02 17:10

    Try this:

    var user = session.Load<User>(1);
    session.Delete(user);
    

    Load will create a proxy for the User object with the identifier set. I'm not sure if Delete will load the object from the database before deleting it and I'm unable to test it at the moment.

    0 讨论(0)
  • 2021-02-02 17:15

    You could do this

    User user = new User();
    user.Id = 1;
    session.Delete(user);
    
    0 讨论(0)
  • 2021-02-02 17:17

    prior to ver 2 there wasn't a way. After ver 2 you have the ExecuteUpdate() method on IQuery and there is an overloaded method on ISession.Delete() where it accepts a string that defines a deletion query

    0 讨论(0)
提交回复
热议问题