0

Here's a scenario that I am working on : Right now we have a SQL statement that reads like this :

SELECT a.ID,a.MsgNumber,CASE WHEN @HasAccess=1 THEN Title ELSE '*********' END AS Title FROM Messages

We want that operators be able to see if a message registered in system but can't see the title if they are not authorized.

I'm changing this part of code so we can use a NHibernate criteria to generate the same result (so we can produce dynamic queries according to filters that user selects). I know that I can use projections to get some fields or constant values from a criteria but can not figure out how I should combine them to do what I want.

Beatles1692
  • 5,214
  • 34
  • 65

1 Answers1

1

It looks like @HasAccess is a parameter passed in by your code, not a value determined by the database. If so, then the easiest way to do what you want is to modify the criteria in code based on the value that you would pass through in the query, eg:

var projections = Projections.ProjectionList()
        .Add(Projections.Id())
        .Add(Projections.Property("MsgNumber"))
        .Add(hasAccess ? Projections.Property("Title") : Projections.Constant("*********"));

var criteria = session.CreateCriteria<Message>()
        .Add(... your restrictions ...)
        .SetProjection(projections)
        .List<object[]>();

If however @HasAccess is determined by your database somehow, then you could use:

Projections.Conditional(Restrictions.Eq("HasAccess", 1),
    Projections.Property("Title"),
    Projections.Constant("*********"))

assuming that you can get HasAccess into your criteria somehow

Martin Ernst
  • 5,629
  • 2
  • 17
  • 14
  • Thanks for you answer I think it will do the job.Here's a question I'd like to ask : How I can set the alias of a projection ? I mean I'd like that Projections.Property("Title") : Projections.Constant("*********")); has the alias title anyway so I can populate a type using Transformers.AliasToBean – Beatles1692 May 22 '12 at 09:07
  • Projections.Constant("***...").As("Title") – Martin Ernst May 22 '12 at 09:08