SubSonic condition expressions
8 Jul
Let’s say I have a table called “Contacts”. I’d like to search that table for the string “michael pardo”, however, I could pass in the string “pardo michael” instead. I’d like it to work either way, so here’s what I think the query should look like:
1 2 3 4 5 6 7 8 9 10 11 12 | SELECT * FROM Contacts WHERE ( FirstName LIKE '%michael%' OR LastName LIKE '%michael%' ) AND ( FirstName LIKE '%pardo%' OR LastName LIKE '%pardo%' ) |
Okay, well how do I enclose those condition expressions with SubSonic? We can take advantage of the Expression syntax to make this work. Here’s the SubSonic code, broken up by query parts.
1 2 3 4 5 6 7 8 9 10 11 12 | // SELECT * FROM Contacts var q = new Select().From<Contact>(); // WHERE (FirstName LIKE '%michael%' OR LastName LIKE '%michael%') q.WhereExpression(Contact.Columns.FirstName).Like("%michael%"); q.Or(Contact.Columns.LastName).Like("%michael%"); // AND (FirstName LIKE '%pardo%' OR LastName LIKE '%pardo%') q.AndExpression(Contact.Columns.FirstName).Like("%pardo%"); q.Or(Contact.Columns.LastName).Like("%pardo%"); q.ExecuteTypedList<Contact>(); |
One problem I encountered with this method was with chaining. If I chain the “or” commands instead of calling them separately, SubSonic will short-change you on the constraints it passes in. Some sort of bug (or feature) maybe.

