I am developing a Console application to programmatically download documents from a SP site among other things. I am trying to retrieve the fields of a content type of a SP list using CSOM :
using (var context = new ClientContext(webUrl))
{
context.Credentials = new NetworkCredential(userName, securePassword, domain);
var web = context.Web;
var list = context.Web.Lists.GetByTitle(listTitle);
context.Load(list);
ContentTypeCollection lstContentTypes = list.ContentTypes;
context.Load(lstContentTypes, l => l.Include(
c => c.Name,
c => c.Fields));
context.ExecuteQuery();
var contentType = lstContentTypes.Where(ct => ct.Name == contentTypeName).FirstOrDefault();
}
I get the following error:
System.NotSupportedException Message=Invalid usage of query execution. The query should be executed by using ExecuteQuery method on the client context object.
Here is the line of code that is causing the problem :
var contentType = lstContentTypes.Where(ct => ct.Name == contentTypeName).FirstOrDefault();
This is driving me crazy. I am working on a local variable that has the content types of the said list. My Load and ExecuteQuery have been executed successfully before the exception is thrown. What does the client context object have to do with it?
NB : The exact same code works perfectly in a WinForms application. Environment : .NET 4.5.2, VS 2019, VS 2015