简体   繁体   中英

SharePoint Lookup ListItem not loading value

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;

I got it solved now.

It seems that this line, context.ExecuteQuery(); , was causing trouble and I was prematurely executing the query before the ListItem was updated.

So I changed my GetItemId function to update the ListItem before doing anything.

private static int GetItemId(SP.ClientContext context, string columnName, string displayName, string listName, SP.ListItem thisItem)
{
    thisItem.Update();

    //this rest of the code is the same
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM