Monday, December 17, 2018

Sharepoint CAML: query against UserMulti field types using Camlex

Sometime we need to query list items against fields which have UserMulti type. In order to do that with Camlex we will use support of LookupMulti field types added few years ago in Camlex (see Camlex 4.2 and Camlex.Client 2.2 are released) and knowledge about behavior of Eq operator when it is used with multi lookup fields: Multi lookup fields in CAML queries. Eq vs Contains. Briefly when Eq operator is used with LookupMulti field types it has different semantic: instead of matching list items which actually equal to specified value it will match items which include this value. Consider the following example:

User user = web.EnsureUser(userName);
var query = new CamlQuery();
query.ViewXml = Camlex.Query().Where(x => x["TestField"] == (DataTypes.LookupMultiId)user.Id.ToString()).ToString(true);
var listItems = list.GetItems(query);

It will produce the following Caml query:

        <FieldRef Name="TestField" LookupId="True" />
        <Value Type="LookupMulti">4/Value>

At first it searches for the user by user name and then uses userId for creating the query. This query will return all items which include user with specific user id (in example above userId = 4) in TestField which has UserMulti type. This field may contain only this user or it may contain several users including those which we are searching for – in both cases list item will be returned. This was one of the reasons of why support of Includes keyword was not added to Camlex – there is no need for that as the same result may be achieved with simple Eq operator.

No comments:

Post a Comment