11

I am working on a project where the ClientContext might be active for a long time. To prevent memory usage getting out of hand I would like to use ClientContext.LoadQuery() instead of ClientContext.Load() when getting items from SharePoint.

LoadQuery works very well when loading lists of items such as Web.Lists or Web.Webs but I haven't found a way to load a single object such as ClientContext.Web. Loading a single website with Load() I would use the following:

string relativeUrl = "/mysite";
Web web = ctx.Site.OpenWebUsingPath( relativeUrl );
ctx.Load(web, w => w.Title);
ctx.ExecuteQuery();

With LoadQuery() I had hoped I could do something like

string relativeUrl = "/mysite";
Web tmpWeb = ctx.Site.OpenWebUsingPath( relativeUrl );
Web web = ctx.LoadQuery(tmpWeb, w => w.Title);
ctx.ExecuteQuery();

That is not possible since LoadQuery takes either IQueryable<T> or ClientObjectCollection<T> as input.

Is there any way to get the web object without having it bound to to the client context and using unnecessary memory?

3

TLDR:

Consider disposing of the context and creating a new one after calls to context.Load as a way to manage memory of objects cached in the context.

Research notes:

There does not appear to be an easy way to convert from a ClientObject to a ClientObjectCollection<T>. Here is what I tried unsuccessfully incase anyone else wants to research further:

Creating an appropriate descended of ClientObjectCollection<T> and populating it with the ObjectPath of the ClientObject produces syntactically correct code which isn't supported by the server and generally returns "Invalid operation" error from ExecuteQuery.

e.g.

string relativeUrl = "/mysite";
Web tmpWeb = ctx.Site.OpenWebUsingPath( relativeUrl );
WebCollection wc = new WebCollection(ctx,tmpWeb.Path);
ctx.LoadQuery(wc.Include( w=>w.Title ));
ctx.ExecuteQuery();

compiles but fails when executed.

It is notable that DataRetrieval.Load<T> (which is what ClientContext.Load<T> calls) does the following on it's first line:

ClientObjectCollection objectCollection = (object) clientObject as ClientObjectCollection;

But this is the non-generic base class for ClientObjectCollection<T>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.