Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an object by using PK in nhibernate?

Tags:

nhibernate

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
like image 864
jgauffin Avatar asked Jun 17 '10 16:06

jgauffin


2 Answers

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

like image 60
Diego Mijelshon Avatar answered Sep 19 '22 18:09

Diego Mijelshon


You could do this

User user = new User();
user.Id = 1;
session.Delete(user);
like image 31
Claudio Redi Avatar answered Sep 23 '22 18:09

Claudio Redi