Using Linq on a Client Object model result from sharepoint

ruffen picture ruffen · Jan 25, 2012 · Viewed 9k times · Source

I am trying to use LINQ on a result i get from Client Object Model.

var rolesAssignments = context.Web.RoleAssignments;
context.Load(rolesAssignments, 
    roles => roles.IncludeWithDefaultProperties(role => role.Member,
    role => role.RoleDefinitionBindings));
context.ExecuteQuery();
var hasAdmin = rolesAssignments.Select(x => x.RoleDefinitionBindings.Cast<RoleDefinition>().Select(y => y.RoleTypeKind == RoleType.Administrator)).Any();

I get:

{System.NotSupportedException: Invalid usage of query execution. The query should be executed by using ExecuteQuery method on the client context object.

However, when i rewrite this to use a nested foreach loop, it works fine.

From what i can see from my linq query, im not using any properties thats not loaded.

Answer

Tommi picture Tommi · Apr 5, 2013

Sorry for necroposting, but I just faced this issue and was not able to find an answer here. The reason why your linq queries failed is client model collections implemented multiple iterators. And when you try enumerate your rolesAssignments you call IQueryable<T> extension methods. This methods (I assume) designed to pull data from server via some incapsulated soap calls and should not be used on client. Istead you should explicitly use extension methods of IEnumerable<T>. So, this will not work:

var hasAdmin = rolesAssignments.Select(predicate);

And this will work:

var hasAdmin = ((IEnumerable<RoleAssignment>)rolesAssignments).Select(predicate);