首页 > 解决方案 > 错误:将查找字段添加到列表时,“对象在与对象关联的上下文不同的上下文中使用”

问题描述

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

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");"

标签: sharepointcsom

解决方案


似乎“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();
}

在此处输入图像描述 在此处输入图像描述


推荐阅读