Can someone explain the differences or the reasons why there're the two methods ClientContext.Load
and e.g. for ListItems ListItem.RefreshLoad()
? Is there a difference?
Why has the ClientContext no equivalent .Update
or Delete
methods?
And when do I have to call the ClientContext.ExecuteQuery
method?
ListItem item = ...;
// 1. Is there a difference between ClientContext.Load(ListItem) and ListItem.RefreshLoad()?
clientContext.Load(item);
item.RefreshLoad();
// 2. Why aren't there methods like ClientContext.Update(...) or ClientContext.Delete(...)?
item.Update();
item.DeleteObject();
// 3. When is the ClientContext.ExecuteQuery needed (load / update / delete)?
clientContext.ExecuteQuery();
Thank you!
The main thing to realize is that the client object model is designed to be asynchronous from the get go.
Think of your client context object as a vessel for sending instructions and receiving data. The .Load()
method queues up instructions, such as .Load(item)
queuing up the instructions to retrieve data about a given list item.
The .ExecuteQuery()
and .ExecuteQueryAsync()
methods send those queued instructions and retrieve the results from the server.
Those operations are different from the operations you can perform against actual SharePoint objects, such as lists and list items. Consider this example from Microsoft:
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newListItem = targetList.AddItem(itemCreateInfo);
newListItem["Title"] = "New Announcement";
newListItem["Body"] = "Hello World!";
newListItem.Update();
clientContext.Load(newListItem);
clientContext.ExecuteQuery(); // only at this point is the item actually created
When you create a ListItem
object in the client object model, all you're doing is creating an object in local memory-- you haven't sent anything to the server yet to actually create an item in the list. The ListItem
object is just a placeholder, and anything you do to it (such as create it and set its field values in the example above) is stored as instructions that need to be carried out.
When you load that object into a client context object (via clientContext.Load(newListItem)
you're just feeding those instructions to your Client Context. Once you run clientContext.ExecuteQuery()
, those instructions are carried out and the placeholder object gets populated with any actual relevant data returned from the server.