SharePoint Caveats – 2: Generating CAML query from LINQ to SharePoint

I was always thinking about how to compare 2 fields(columns) of a SharePoint list using CAML queries. But got to know that it can be accomplished using LINQ to SharePoint but not CAML. I have also blogged about it over here. You can read this blog on how to use the LINQ to SharePoint feature to query SharePoint lists. But it is said that the LINQ query itself would get converted in to a CAML query at run time. I saw this blog which explains about how to write a CAML query generated from LINQ to SharePoint in to a text file.

So, I thought of writing a LINQ query to compare 2 fields(columns) and see what CAML query gets generated from it. I wrote the below program which compares 2 fields(columns) in an SP List called Spwitter using LINQ to SharePoint and logs the CAML query to an XML file.

using (var dataContext = new MySPDataContext("http://localhost:1446/"))
            {
                    TextWriter textWriter = new StreamWriter(@"c:\caml.xml", false);
                    dataContext.Log = textWriter;
                    var result = from c in dataContext.SpwitterList
                                 where  c.Title != c.Spweet
                                 select c;

                    foreach (var item in result)
                    {
                        System.Console.WriteLine("{0}----{1}", item.Title, item.Spweeter);
                    }
           }

I opened the caml.xml file with an excitement to see what CAML query has got generated for comparing 2 fields(columns) and saw the below query in it 😦 which does not have anything related to comparing 2 SharePoint list fields.

<View>
  <Query>
    <Where>
      <BeginsWith>
        <FieldRef Name="ContentTypeId" /><Value Type="ContentTypeId">0x0100</Value>
      </BeginsWith>
    </Where>
  </Query>
  <ViewFields>
    <FieldRef Name="Spweet" /><FieldRef Name="Spweeter" />
    <FieldRef Name="ImageURL" /><FieldRef Name="ID" />
    <FieldRef Name="owshiddenversion" />
    <FieldRef Name="FileDirRef" />
    <FieldRef Name="Title" />
  </ViewFields>
  <RowLimit Paged="TRUE">2147483647</RowLimit>
</View>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s