The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  83 Posts :: 0 Stories :: 56 Comments :: 2 Trackbacks

Ads

 

Donate via PayPal...

...if you feel the site helped.

Archives

Post Categories

Open Source Projects

Other Blogs

Wow – it seems like last year just flew by. I opened LiveWriter this morning and realised that I last posted an article in June 2011, and that I have 14 incomplete articles that I’ve never got round to completing.

To kick off the year, I’m going to start off with (what I think) is an underused class in Castle ActiveRecord (actually, it resides from NHibernate) – Disjunction.

The Disjunction type can be used to construct large 'OR' statements for use in ActiveRecord data retrievals. If you have used this class before, you may have noticed that any ‘OR’ operations that have more than two boolean operation that you’ve wanted to perform end up looking like this:

    var criteria = Restrictions.Or
        (
        Restrictions.Or(Restrictions.Like("Firstname", "Foo"), Restrictions.Like("Lastname", "Foo")),
        Restrictions.Or(Restrictions.Like("Firstname", "Bar"), Restrictions.Like("Lastname", "Bar"))
        );
 
    var person = Person.FindAll(criteria);

The example above ends up producing some unnecessary code clutter to essentially come up with the SQL statement:

WHERE 
   Firstname LIKE '%Foo%' OR
   Firstname LIKE '%Bar%' OR
   Lastname  LIKE '%Foo%' OR
   Lastname  LIKE '%Bar%'

Using the Disjunction class, you can modify the original example to look like this:

            var criteria = new Disjunction();
            criteria.Add(Restrictions.Like("Firstname", "Foo"));
            criteria.Add(Restrictions.Like("Firstname", "Bar"));
            criteria.Add(Restrictions.Like("Lastname", "Foo"));
            criteria.Add(Restrictions.Like("Lastname", "Bar"));
 
            var person = Person.FindAll(criteria);

In my opinion: better looking code and, although it’s not quite made evident in the examples above, it makes for much easier programming. Image that you were searching 5 fields for three keywords – the “tree” that you’ve effectively built in the first example would start looking horrendous and would be a nightmare to maintain.

posted on Friday, January 20, 2012 8:53 AM

Feedback

# re: Constructing a large OR statement in Castle ActiveRecord 1/25/2012 6:20 AM Mohamed samir
thanks for your help

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 5 and 4 and type the answer here: