Wesley Tansey
Wesley Tansey

Reputation: 4605

Fluent NHibernate Custom SQL Query

I'm new to NHibernate and FNH. I'm trying to query for multiple possible objects in a single query and I am not sure what the most efficient query is. I have a dictionary of words:

public class Word
{
   public virtual int Id { get; set; }
   public virtual string Text { get; set; }
}

And I want to query for all Word objects that are contained in a list. The SQL I have is:

SELECT (*) FROM dbo.Word WHERE Text LIKE 'word1%' OR Text LIKE 'word2%' ...

Right now I'm just getting the list of words and generating the WHERE clause of the SQL query. I've created an ISQLQuery but I'm not sure how to execute it and get back a collection of Word objects.

Upvotes: 0

Views: 2265

Answers (1)

Vadim
Vadim

Reputation: 17957

Since you're using NHibernate why not use the facilities provided for you rather than writing custom SQL that is likely prone to SQL injection.

public IList<Word> GetWords(IList<string> filters)
{
    var criteria = Session.CreateCriteria<Word>();
    var disjunction = Restrictions.Disjunction();
    foreach (var filter in filters)
    {
        disjunction.Add(Restrictions.Like("Text", filter, MatchMode.Start));
    }
    criteria.Add(disjunction);

    return criteria.List<Word>();
}

Upvotes: 3

Related Questions