Kenneth Van Coppenolle
Kenneth Van Coppenolle

Reputation: 166

Updating lookup fields of SharePoint list items using REST in C#

I am using a service reference to listdata.svc to manipulate SharePoint lists. I have a list for companies and a list for people.

I can manipulate the data like this:

HomeDataContext proxy = new HomeDataContext(new Uri(url + "/_vti_bin/listdata.svc"));
proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
PeopleItem person = proxy.People.Where(p => p.Name.Equals(myName)).First();
PeopleItem boss = proxy.People.Where(p => p.Name.Equals(bossName)).First();
CompaniesItem company= proxy.Companies.Where(c => c.ID.Equals(companyName)).First();
company.Employees.Add(person);
company.Boss = boss;
company.Name = "New Name";
proxy.UpdateObject(company);
proxy.SaveChanges();

With this method I can edit basic properties of my listitems (like Name). However, I can't use this to update lookup fields (like Boss or the multiple lookup Employees). In the object model, it all appears to work and no exceptions are thrown, but after updating and saving, the fields are simply blank in SharePoint.

Upvotes: 1

Views: 2281

Answers (2)

Kris
Kris

Reputation: 31

That above example isn't going to work. for a single value look up field you need to set the id property.

For the company to have a look up to the boss you will need to go

company.BossId = boss.Id;

the above example won't write the changes to the sharepoint list, with lookup fields you need to set the Id property.

Upvotes: 1

Nirmit Shah
Nirmit Shah

Reputation: 758

If person item is already present in sharepoint and you just want to add it in Company than you can use:

HomeDataContext proxy = new HomeDataContext(new Uri(url + "/_vti_bin/listdata.svc"));
proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
PeopleItem person = proxy.People.Where(p => p.Name.Equals(myName)).First();
PeopleItem boss = proxy.People.Where(p => p.Name.Equals(bossName)).First();
CompaniesItem company= proxy.Companies.Where(c => c.ID.Equals(companyName)).First();
//company.Employees.Add(person);
company.Boss = boss;
company.Name = "New Name";
proxy.UpdateObject(company);
proxy.SaveChanges();
//To remove employee from company
proxy.DeleteLink(company, "Employee", person);
proxy.SaveChanges();
//To Add person as employee
proxy.AddLink(company,"Employee",person);
proxy.SaveChanges();

You can also look at proxy.AddRelatedObject() method to create new person and link simultanously. For more information on these methods: http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.aspx

Upvotes: 0

Related Questions