Write CAML queries in code

less than 1 minute read

In my very first webpart that I wrote I needed to write some CAML queries to filter and sort the lists.

Being the type of guy who hates seeing strings littering my code I searched the net for an API for CAML queries. Thankfully John Holliday had already done the hard work and created CAML.NET. Check out the clean syntax for the CAML code.

   1: string typeName = "My Content Type";
   2: string simpleQuery =
   3:     CAML.Query(
   4:         CAML.Where(
   5:             CAML.Or(
   6:                 CAML.Eq(
   7:                     CAML.FieldRef("ContentType"), 
   8:                     CAML.Value(typeName)),
   9:                 CAML.IsNotNull(
  10:                     CAML.FieldRef("Description")))),
  11:         CAML.GroupBy(
  12:             true,
  13:             CAML.FieldRef("Title",CAML.SortType.Descending)),
  14:         CAML.OrderBy(
  15:             CAML.FieldRef("_Author"),
  16:             CAML.FieldRef("AuthoringDate"),
  17:             CAML.FieldRef("AssignedTo",CAML.SortType.Ascending))
  18:     );

Here again you might run into the issue of adding an extra assembly to your deployment, the simple alternative that I took was to include the CAML class directly into me source tree. But remember to keep the copyright and license header in place as stated by the Ms-CL license.

Hopefully Microsoft will release a Linq to CAML library soon, there is already one at CodePlex by a Microsoft employee but what would be better is if it comes with SharePoint.