Reputation: 8003
What's the best practice in NHibernate to delete an object by id. You can do both
public void Delete(int id)
{
Session.Delete(new MyEntity { Id = id });
}
Or you could do
public void Delete(int id)
{
var entity = Session.Get<MyEntity>(id);
Session.Delete(entity);
}
The second option feels cleaner to me, because you're not composing a new object just for deletion, but on the other hand you'll execute two SQL commands, instead of one.
Upvotes: 0
Views: 302
Reputation: 49251
The second option is the best practice. NHibernate needs to load the object before deleting it so that it cascade deletes through the object graph. I would rather do a direct SQL delete than create a bogus object to trick NHibernate as in the first option.
Upvotes: 2