Let's say I have two lists with following fields:
List A
------
+ Title
+ MultiLookupOnListB (Lookup List: List B; Lookup Field: Title)
List B
------
+ Title
+ LookupOnListA (Lookup List: List A; Lookup Field: Title)
So basically a List A Item can reference one or more List B Items while a List B Item can only reference one List A Item. I already set List B -> List A lookup with CSR, but the List A -> List B lookup needs to be done in an event receiver since I need access to resources that aren't available when using JS.
So I use ItemUpdating for adding List B items to List A multi lookup field. Only problem is, when two list items are created at the same time, the code is too fast (^^) and the second event basically overwrites the first event so I end up with only one referenced List B Item.
/// <summary>
/// An item was updated.
/// </summary>
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
var listItem = properties.ListItem;
var listAItem = GetListAItemFromSomewhere();
SPFieldLookupValueCollection listItemALookup = listAItem["MultiLookupOnListB "] as SPFieldLookupValueCollection;
if (listItemALookup.OfType<SPFieldLookupValue>().Where(pdr => pdr.LookupId == listItem.ID).Count() < 1)
{
listItemALookup.Add(new SPFieldLookupValue(listItem.ID, listItem.Title));
listAItem["MultiLookupOnListB "] = listItemALookup;
listAItem.SystemUpdate(false);
}
}
I have already tried to set the ItemUpdating event to synchronous, but that didn't work. So, any ideas on how to best do this?