使用 CSOM 将查找列添加到列表 [英] Adding lookup column to list using CSOM

查看:45
本文介绍了使用 CSOM 将查找列添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Books"的列表,其中包含Name"、AuthorName"、ISBN"列,类型为文本.现在我有另一个名为BillTokenStore"的列表,我想在BillTokenStore"中添加查找列AuthorName".以下是我所做的.

I have a list called "Books" with columns 'Name','AuthorName','ISBN' with type as text. Now I have another list called "BillTokenStore" and i want to add lookup column 'AuthorName' in "BillTokenStore". Below is what i have done.

using (ClientContext context = new ClientContext(webFullUrl: siteUrl))
            {
                context.Credentials = new SharePointOnlineCredentials(userName, GetPassWord());

                Web web = context.Web;

                ListCollection listCollection = web.Lists;
                List list = listCollection.GetByTitle("BillTokenStore");


                string schemaLookupField = @"<Field Type='Lookup' Name='InStock' StaticName='InStock' DisplayName='InStock' List = 'Books' ShowField = 'Title' /> ";
                Field lookupField = list.Fields.AddFieldAsXml(schemaLookupField, true, AddFieldOptions.DefaultValue);

                context.ExecuteQuery();               
            }

当我运行此代码时,出现错误值不在预期范围内共享点 2013"​​.这里有什么问题?提前致谢.

When i run this code, i am getting the error "value does not fall within the expected range sharepoint 2013". What is wrong here? Thanks in Advance.

注意:我能够通过 UI 实现同样的事情.我还可以添加其他类型的字段,如选择、布尔值和全部通过代码.

Note: I am able to achieve the same thing thorough UI. I am also able to add other type of fields like choice,boolean and all through code.

推荐答案

您需要显式加载列表和该列表的字段.

You need to explicitly load the list and the fields of that list.

另外,我们需要传递查找列列表的 GUID.

Also, we need to pass the GUID of the lookup column list.

请尝试以下修改后的代码:

Please try the below modified code:

using (ClientContext context = new ClientContext(webFullUrl: siteUrl))
{
    context.Credentials = new SharePointOnlineCredentials(userName, GetPassWord());

    Web web = context.Web;

    List booksList = context.Web.Lists.GetByTitle("Books");

    List list = context.Web.Lists.GetByTitle("BillTokenStore"); 

    context.Load(list, l => l.Fields);
    context.Load(booksList, b => b.Id);
    context.ExecuteQuery();

    string schemaLookupField = @"<Field Type='Lookup' Name='InStock' StaticName='InStock' DisplayName='InStock' List='"+ booksList.Id +"' ShowField = 'Title' />";
    Field lookupField = list.Fields.AddFieldAsXml(schemaLookupField, true, AddFieldOptions.DefaultValue);
    lookupField.Update();

    context.Load(lookupField);
    context.ExecuteQuery();     
}

这篇关于使用 CSOM 将查找列添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆