Skip to content

Instantly share code, notes, and snippets.

@johnnonolan
Created January 4, 2012 16:22
Show Gist options
  • Save johnnonolan/1560779 to your computer and use it in GitHub Desktop.
Save johnnonolan/1560779 to your computer and use it in GitHub Desktop.
nh headache
// I'm trying to dynamically build up criteria
ICriteria criteria = session.CreateCriteria<Client>().Add(BuildCriteria(clientParams));
static ICriterion BuildCriteria(IEnumerable<MatchableClientParams> clientParams)
{
var result = Restrictions.Disjunction();
foreach (var parameters in clientParams)
{
MatchableClientParams parameters1 = parameters;
result.Add(Restrictions.InsensitiveLike("LastName",clientParams.SomeTextWithLastNameIn,MatchMode.Anywhere));
}
return result;
}
//This produces SELECT * FROM clients where LastName like '%'+@p1+'%'
//whereas I want
//SELECT * FROM clients where @p1 like '%'+LastName+'%'
@kuangmarkeleven
Copy link

//given
public class ClientParams
{
public string ClientImputText { get; set; }
public string DbField { get; set; }
}

//then

    public IList<Client> GetClient(IEnumerable<ClientParams> clientParams)
    {
        var searchCriteria = GetSession().CreateCriteria<Client>();

        foreach(var p in clientParams)
        {
            searchCriteria.Add(Expression.Sql(string.Format("'{0}' like '%' + {1} + '%'", p.ClientImputText,p.DbField)));
        }
        return searchCriteria.List<Client>();

    }

//does the job given

     var results =
            repository.GetClient(new List<ClientParams>
                                     {
                                         new ClientParams
                                             {
                                                 DbField = "Surname",
                                                 ClientImputText = "Today Carl Griffiths Solved The Mystery"
                                             }
                                     });
    }

//if the db client table has an entry with "Griffiths" as the surname

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment