When designing an application I usually stumble upon a problem I've never quite managed to handle properly.

Suppose you have Products and Orders. Usually in my data-access layer I have repositories that can return back lists of these object already filtered based, for example, the logged user that made the request. When I say "already filtered" I mean that the security-layer of the application (which is a cross-cutting concern) constructed the necessary criteria so that the data-access layer can actually query the db asking for object the logged user can actually see - no other filters are applied in memory.

Suppose that the actual Product class is something like this:

public class Product
    public virtual IList<Order> Orders {get; set;}
    // other stuff 

where the Orders collection contains all orders (from every user) placed on the product.

Now, this presents a problem because by accessing this property I can potentially show a user orders placed by other users.

I usually use NHibernate as an ORM an I cannot find a proper solution to this problem. I'm aware of "filters" but they are just string and not really useful when you need to make something more complex than the contrived example given here for brevity. Unless there is a way to use the criteria api with filters but, as far as I know, it's not possible

  • Why do you even have the list of orders associated to a product? Shouldn't it be the other way around? – Andy Jan 21 '17 at 19:13
  • This is just an example, I do not deal with products or orders. However, one reason could be that I want a handy way to easily access all orders associated to a product. – user260171 Jan 21 '17 at 19:22
  • I don't understand the question. The first part seems to describe a solution to the problem in the second part. How hard is it to parameterize the query in NHibernate? – JimmyJames Mar 23 '17 at 18:09
  • @JimmyJames when you access the Orders property from the Product object (that you retrieved from the db) you don't have any control over the query being executed (not entirely true, there are filters, but are not enough to enforce any kind of meaningful security), so there's no way to filter the orders based on some non-trivial condition. – user260171 Mar 23 '17 at 18:55

I don't know of a way to do this in NHibernate, but generally I don't consider that to be a model concern anyway. Instead, whatever service is called to get the model for the user should be aware of the user that's being called and then only return appropriate info to the user in question by altering query parameters or whatever else you need to do to make it happen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy