I have a list in the rootweb, and a list in a subweb. I want to update/add when something changes in an item in the subweb. This method is invoked in an ItemUpdated event receiver. The problem is that the item is added four times to the rootlist.
/// <summary>
/// Updates an item on a rootweblist, or adds the item if it doesn't exist.
/// </summary>
/// <param name="leafWeb">The web the updated item belongs to</param>
/// <param name="leafItem">The item being updated</param>
/// <param name="rootWebListName">The name of the list in the root web</param>
/// <param name="contentTypeName">Name of the custom content type</param>
/// <param name="fieldsToUpdate">The fields to update</param>
internal void UpdateItemOnRootwebList(SPWeb leafWeb, SPListItem leafItem, string rootWebListName, string contentTypeName, List<string> fieldsToUpdate)
{
//Impersonate system account - Not sure if needed
var systemAccToken = leafWeb.Site.SystemAccount.UserToken;
using (var kundeSiteCol = new SPSite(leafWeb.Site.ID, systemAccToken))
{
using (var rootWeb = kundeSiteCol.OpenWeb())
{
var rootList = rootWeb.Lists.TryGetList(rootWebListName);
if (rootList != null)
{
//Find the corresponding item on rootlist, or create a new if it doesn't exist
var listItems = rootList.Items;
var rootItem = listItems.Cast<SPItem>().FirstOrDefault(and => and["Title"] == leafItem["Title"]);
if (rootItem == null) rootItem = listItems.Add();
//Set content type
var itemType = rootList.ContentTypes[contentTypeName];
rootItem["ContentTypeId"] = itemType.Id;
//Update the relevant fields
foreach (var field in fieldsToUpdate)
{
rootItem[field] = leafItem[field];
}
//Update the item, or add if it doesn't exist
rootItem.Update();
}
}
}
}
Update: Rephrased the question tremendously.