views:

121

answers:

6

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

In another ORM, I can do this:

session.Delete<User>(1); // 1 = PK
A: 

here is a blog entry about this : http://cephas.net/blog/2004/06/01/hibernate-deleting-objects/

redben
Yes. I've googled that myself too. There must exist a more elegant way to do it than to have to write hql/sql by yourself.
jgauffin
Well then @Claudio [answered][1], if you don't want to do it that way, then loadthe object and call delete.[1]http://stackoverflow.com/questions/3063777/how-to-delete-an-object-by-using-pk-in-nhibernate#3063827
redben
+1  A: 

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.

Frederik Gheysels
+1  A: 

You could do this

User user = new User();
user.Id = 1;
session.Delete(user);
Claudio Redi
A: 

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.

Jamie Ide
I'm afraid it does load it.
Diego Mijelshon
+3  A: 

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).

Diego Mijelshon
A: 

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

Jaguar