Search code examples
c#nhibernateicriteria

nHibernate Criteria Query OR or IN?


I need to recreate a query using nHibernate Criteria. This query had a where clause that was pretty ugly.

((t.Disposition_CD)='ac' Or    
 (t.Disposition_CD)='cc' Or  
 (t.Disposition_CD)='Co' Or  
 (t.Disposition_CD)='SF' Or  
 (t.Disposition_CD)='SC' Or  
 (t.Disposition_CD)='OR' Or  
 (t.Disposition_CD)='SV' Or  
 (t.Disposition_CD)='RI' Or  
 (t.Disposition_CD)='WN' Or  
 (t.Disposition_CD)='NC' Or  
 (t.Disposition_CD)='DN' Or  
 (t.Disposition_CD)='WT' Or  
 (t.Disposition_CD)='MA' Or  
 (t.Disposition_CD)='TO' Or  
 (t.Disposition_CD)='OC'))

so, I started here

IList leadList = 
     session.CreateCriteria(typeof(Lead)).Add(Expression.In("CallDisposition", 
     new string[] {"AC","CC" })).List();

the problem the Property on Lead is a CallDisposition Object and gives me a Unknown entity class: System.String error when I try to do this. An Array of CallDisposition is what it's looking for.

Basically what I'm looking for is a list of Leads that meet all the or criteria of the original query. Any suggestions are helpful.


Solution

  • Without knowing the properties of your entities it is hard to comment.

    If the CallDisposition property is a CallDisposition entity that has a CallDispostionCode property then you could do something like this:

    IList leadList = session.CreateCriteria(typeof(Lead))
       .Add(Expression.In("CallDisposition.CallDispostionCode", 
                          new string[] {"AC","CC" })).List();
    

    Or if CallDisposition has an Id you could modify your second solution to something like this:

    DetachedCriteria criteria = DetachedCriteria.For<CallDisposition>()
        .Add(Expression.In("CallDispostionCode", new string[] { "AC", "CC" })
        .SetProjection(Projections.Property("CallDisposition.Id"));
    
    IList leadList = session.CreateCriteria(typeof(EmcLead))
        .Add(Subqueries.PropertyIn("CallDisposition.Id", criteria)).List();
    

    This would be only one database hit using a subselect.