SPListItem.Update()
Now thats a funny title. This is something I worked on quite recently. Consider a scenario where you are trying to access a number of lists programmatically. The issue I dealt with was concerned with lists in a recurring event of a metting workspace. But subsequent research revealed that this is a generic issue.
So, you are accessing lists programmatically. Amongst say four lists (list1, list2, list3, list4, for example) you fetch the properties list ID, etc of list1. Now, you decide to change say the ist name and fire a SPList.Update() . After this is done, you decide to see the details for say List3. Oops, what happened to list3 details you are actually seeing details of all the lists! You recheck your code..no, you are not missing the identifier for list3 so what went wrong here?
Here is what your code would look like
SPSite site = new SPSite(strUrl);
SPWeb web = site.OpenWeb();
SPList list = web.Lists[strListName];
// use SPQuery to query the list
SPListItem item;
SPListItemCollection items = list.Items;
if(items.Count > 0 )
{
item = items[0];
// make some changes to this item
item.Update();
}
// use SPQuery to query the list again
Why the query does not return proper results has to do with the way the cache is refreshed. This being one of the mystical disciplines, not much is clear. But one thing we know, is after the first query (the one that returns incorrect results), all subsequent ones are going to return correct results.
A possible explaination is that when the update executes, it executes on the database and makes the changes. However, owing to performance considerations, the list details are already in the cache. So now, we have two copies, the one in the cache which is dirty and the other in the database. At this point the cache still doesnt know that the database has been modified. So the query that executes is going to just run through the cache and pull up all the data. What is still mystical is that it pulls up everything and not just the concerned list.
Another interesting bit here is it doesnt matter which list you update.
So now you try to put in a wait before the next query executes...still no luck! this being as mystical as it is, there is no guideline on when the cache is going to get refreshed. Now, we need a workaround. Fetch the details yourselves and hence update the cache. Simple?..yup it is simple.
Just add the following line after the update...
items = list.Items;
What this is going to do is fire a query internally to update the cache. This in effect takes care of the update problem and you are raring to go. Case closed!
--/H
Comments
- Anonymous
May 15, 2006
thanks a lot !
this is my code:
if(list.Items.Count>0)
{
SPListItem newItem = list.Items[0];
newItem["文件名稱"] = strDName; newItem.Update();
}
else
{
SPListItem newItem = list.Items.Add();
newItem["文件名稱"] = strDName;
newItem.Update();
}
haha! it's ok!