Load vs Loadquery
The LoadQuery method
works in much the same way as the Load method, but it allows the client to
process the queries more efficiently. The main difference is that the Load
method populates the client object or client object collection that is passed
into it. The LoadQuery method instead returns an entirely new collection of
client objects. To get a clarification of these differences, examine the
following examples for .NET managed code.
Retrieving the Number of
Lists via the Load Method
class Program
{
static void Main(string[] args)
{
ClientContext ctx = new ClientContext(“http://server”);
ctx.Load(ctx.Web.Lists);
ctx.ExecuteQuery();
Console.WriteLine(“” + ctx.Web.Lists.Count);
Console.ReadLine(“Press RETURN…”);
}
}
{
static void Main(string[] args)
{
ClientContext ctx = new ClientContext(“http://server”);
ctx.Load(ctx.Web.Lists);
ctx.ExecuteQuery();
Console.WriteLine(“” + ctx.Web.Lists.Count);
Console.ReadLine(“Press RETURN…”);
}
}
In the above example
Console.WriteLine(“” + ctx.Web.Lists.Count); will write the count of lists in
the web since the ctx.Web.Lists gets loaded with the lists in the context.
Now lets see the other
example, which uses the LoadQuery method, which is also initialized with the
ctx.Web.Lists object. However, after the query is executed, the lists are
returned as a completely new client object collection. If you try to directly
access the property ctx.Web.Lists.Count, a CollectionNotInitialized exception
is raised. This implies that, unlike in the above code, the original
ctx.Web.Lists property has not been populated. Instead, a new allLists
collection has been created and populated.
Retrieving the Number of
Lists via the LoadQuery Method
class Program
{
static void Main(string[] args)
{
ClientContext ctx = new ClientContext(“http://server”);
IEnumerable allLists = ctx.LoadQuery(ctx.Web.Lists);
ctx.ExecuteQuery();
Console.WriteLine(“” + allLists.Count());
Console.ReadLine(“Press RETURN…”);
}
}
{
static void Main(string[] args)
{
ClientContext ctx = new ClientContext(“http://server”);
IEnumerable allLists = ctx.LoadQuery(ctx.Web.Lists);
ctx.ExecuteQuery();
Console.WriteLine(“” + allLists.Count());
Console.ReadLine(“Press RETURN…”);
}
}
The advantage of
LoadQuery over the Load method is its flexibility, especially when working with
more than one query. It gives you better control over memory consumption, and
query processing is more efficient. Consider garbage collection: the Load
method populates objects that reside within the ClientContext instance. Those
objects can only be cleaned up when the ClientContext instance is destroyed.
Conversely, objects created by LoadQuery are separate from the ClientContext
instance and can be destroyed much more readily, for example by setting them to
NULL.