错误:在列表中添加查找字段时,“该对象在与该对象关联的上下文中使用的上下文不同”

时间:2019-11-04 04:00:36

标签: sharepoint csom

在以下代码中,我想将查找字段添加到列表中。但是,它得到了一个错误:“该对象在与该对象关联的上下文中使用的上下文不同”。但是,我不知道我在哪里弄错了。有人可以告诉我吗?

ClientContext context = new ClientContext("samplesite");
SecureString password = new SecureString();
foreach (char c in "abcdxyz".ToCharArray()) password.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("abcd@xyz.com",password);            
FieldLookup emp = context.CastTo<FieldLookup>(context.Site.RootWeb.Lists.GetByTitle("Employees").Fields.GetByTitle("First Name"));
context.Load(emp);
context.ExecuteQuery();
projs.Fields.AddDependentLookup("Leader", emp, "Employee");
emp.AllowMultipleValues = true;
projs.Fields.AddDependentLookup("Members", emp, "Employee");
context.ExecuteQuery();         

Ps:控制台在以下行显示错误的地址:“ projs.Fields.AddDependentLookup(” Leader“,emp,” Employee“);”

2 个答案:

答案 0 :(得分:0)

似乎“ projs”是列表对象,所以我进行了如下测试:

using (ClientContext ctx = new ClientContext("https://tenant.sharepoint.com/sites/dev/"))
{

                ctx.Credentials = new SharePointOnlineCredentials(account, secret);
                ctx.Load(ctx.Web);
                ctx.ExecuteQuery();
                FieldLookup emp = ctx.CastTo<FieldLookup>(ctx.Site.RootWeb.Lists.GetByTitle("MyList").Fields.GetByTitle("MyLookup"));
                ctx.Load(emp);
                ctx.ExecuteQuery();
                ctx.Site.RootWeb.Lists.GetByTitle("MyList").Fields.AddDependentLookup("MyID", emp, "ID");
                emp.AllowMultipleValues = true;
                ctx.Site.RootWeb.Lists.GetByTitle("MyList").Fields.AddDependentLookup("MyCreatedDate", emp, "Created");
                ctx.ExecuteQuery();
}

enter image description here enter image description here

答案 1 :(得分:0)

当我尝试使用不同的 ClientContext 加载客户端对象时出现此错误。因此请确保 projs 使用相同的 ClientContext。