13

I have a use case where a user gets a list of products, and can select multiple products and active or deactivate them.

The model for this list is immutable, and I have a repository which takes a list of the model that should deactivate them all.

I do have another full product editing model, but I'd rather not have to load up hundreds of those to simply change one column.

I'm concidering using Session.CreateQuery, but is there a better way to acomplish this?

2 Answers 2

32

HQL is the way to go.

Session.CreateQuery("update Product set Active = :active where id in (:ids)")
       .SetParameter("active", active)
       .SetParameterList("ids", listOfSelectedProductIds)
       .ExecuteUpdate();
Sign up to request clarification or add additional context in comments.

9 Comments

Is there a way without HQL? I'd like to use the mappings already in place instead of writing inline queries, which was the idea behind an ORM in the first place.
One of the main purposes of an ORM is to avoid writing queries. Your solution combines all of the anti-patterns in one package: 1) inline DB statement; 2) using a huge abstraction layer - NH - to essentially call an easy SQL statement - for no good reason and with a huge cost; 3) not using the data model mappings. (please don't take offense)
@mr.ta, you couldn't be more wrong. HQL is not a DB statement, it's part of the ORM, and it USES THE MAPPINGS (you refer to classes and properties, not tables). No offense, but please read the NH docs.
You're missing the point. The fact that it uses the mappings to perform what is essentially a glorified string Replace operation makes it worse, not better. Yes it uses mappings, which means all of the overhead of abstraction layers, but it still makes you write an inline query (even if it's "HQL"), which means all of the unreliability and unmaintainability of inline queries.
Suit yourself. Again, I'm not out to get you, and your answer is a valid answer - even if I think it's a bad approach.
|
8

Since NHibernate 5, you can use LINQ for updates/deletes, like this:

session.Query<Product>()
    .Where(p => listOfSelectedProductIds.Contains(p.Id))
    .Update(p => new { Active = active });

It will not load entities or increment versions.

https://nhibernate.info/doc/nhibernate-reference/querylinq.html#querylinq-modifying

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.