I am importing a database into SharePoint Lists. I have a list of Plants that are owned by Companies.
Plants have columns for "Plant Name", "Company", "State", "Address", and so on. "Plant Name" and "Address" are both single text lines but "Company" and "State" are lookup types. The "Company" column should look up a name on the "Company" list and link to it. The same for the "State" column linking to the "State" list.
Here is a snippet of my code:
SP.ClientContext context = new SP.ClientContext("http://localhost");
...
newPlantLocation["Company"] = GetItemId(context, "Title", companyName, "Companies");
newPlantLocation["State"] = GetItemId(context, "Title", plantState, "States");
newPlantLocation["Title"] = plantName;
newPlantLocation["Address_x0020_Line_x0020_1"] = plantAddressLine1;
...
newPlantLocation.Update();
and here is the function that returns the ID of the item, it's not the most efficient but easy to follow:
private static int GetItemId(SP.ClientContext context, string columnName, string displayName, string listName)
{
SP.List list = context.Web.Lists.GetByTitle(listName);
SP.CamlQuery query = new SP.CamlQuery();
SP.ListItemCollection items = list.GetItems(query);
context.Load(items);
context.ExecuteQuery();
foreach (SP.ListItem listItem in items)
{
if (listItem[columnName].Equals(displayName))
{
return listItem.Id;
}
}
return 0;
}
The problem that I'm coming across is that when the importer runs, the plants populate the "Plants" list but the "Company" field is left blank. I'm confused because the "State" field is done pretty much the same way and it somehow ends up populated. I've debugged it and the GetItemId function returns the correct integer of the company, it just isn't showing up or saving to the item.
If I do the following, it all of a sudden starts working:
newPlantLocation["Company"] = 4;