Below are two samples on how to create a query with ActiveRecord and ICriterion.
Example 1: Select all contacts from Texas
public static Contact[] FindByState(string State)
{
ICriterion[] query = { Expression.Eq("State", State) };
Order[] sort = { Order.Asc("LastName") }
return Contact.FindAll(sort, query);
}
The Controller’s syntax would be this:
Contact[] contacts = Contact.FindByState("TX");
Example 2: SQL style query
ArrayList stateslist = new ArrayList();
stateslist.Add("TX");
stateslist.Add("VA");
The next part is where all the magic happens. The “SELECT” part is done for us automatically, so we simply add our WHERE clause. In the example you’ll notice the parameter format (:variablename). The in parameter is wrapped with parentheses:
string hql = String.Format("FROM Contact c where State in (:states)");
SimpleQuery<Contact> q = new SimpleQuery<Contact>(hql);
q.SetParameterList("states", stateslist);
q.SetQueryRange(25);
Contact[] result = q.Execute();
If we wanted to execute a LIKE search:
string hql = String.Format("FROM Contact c LastName like :lastname");
...
q.SetParameter("lastname", stringvalue + "%");
...
Here is some further reading on HQL:
- http://www.castleproject.org/ActiveRecord/documentation/v1rc1/usersguide/hql.html
- https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html_single/#d0e8963
