Compartilhar via


Multiple DataContext Objects for the Same SharePoint Website (Ricky Kirkham)

Using the LINQ to SharePoint provider to read and write data poses a dilemma: queries run faster if the object change tracking system has been turned off for the Microsoft.SharePoint.Linq.DataContext object that represents the website, but if it is turned off, you cannot write data to the website’s lists. Moreover, you cannot change the value of the DataContext.ObjectTrackingEnabled property between true and false as you switch between writing-to and querying the lists: once a query has been executed with the ObjectTrackingEnabled property set to false, it cannot be set to true again.

You can, however, have two distinct DataContext objects that represent the very same website. This enables you to disable the object change tracking system for one object and use it solely for querying. Of course, you would leave the property enabled (the default) on the other object and use that object solely for write operations on the lists.

The following code illustrates how to do this.

DataContext dc = new DataContext("https://localhost");            

// Disable object change tracking.
dc.ObjectTrackingEnabled = false;

EntityList<ManagersItem> allManagers = dc.GetList<ManagersItem>("Managers");

// Query for each manager with a “B” in his or her name.
var filteredManagers = from manager in allManagers
where manager.Title.Contains("B")
select manager;

foreach (var manager in filteredManagers)
{
Console.WriteLine("{0} is the name of a manager.", manager.Title);
}

// Get a second DataContext for the same Web site. Do not disable object change tracking.
DataContext dc2 = new DataContext("https://localhost");

// Get a second reference to the Managers list.
EntityList<ManagersItem> allManagers2 = dc2.GetList<ManagersItem>("Managers");

// Create a new manager with a “B” in his name
ManagersItem newManager = new ManagersItem() { Title = "Bob Smith" };

// Add the new manager to the list using the object-tracked DataContext
allManagers2.InsertOnSubmit(newManager);
dc2.SubmitChanges();

// Re-execute the query on the first DataContext.
// The new manager will appear on the list.
foreach (var manager in filteredManagers)
{
Console.WriteLine("{0} is the name of a manager.", manager.Title);
}

// Remove the new manager using the object-tracked DataContext.
foreach (ManagersItem existingManager in allManagers2)
{
if (existingManager.Title == "Bob Smith")
{
allManagers2.DeleteOnSubmit(existingManager);
}
}

dc2.SubmitChanges();

// Re-execute the query on the first DataContext.
// The new manager is gone again.
foreach (var manager in filteredManagers)
{
Console.WriteLine("{0} is the name of a manager.", manager.Title);
}

Comments

  • Anonymous
    July 22, 2011
    The comment has been removed