Monday, September 6, 2010

How to update lookup column through LINQ in SharePoint 2010

To update lookup field through LINQ, there is a tricky issue: we need to update "Display" column instead of "ID".

Below is the sample code.  The column "Animal" is a lookup column.

                using (ServerDataContext ctx = new ServerDataContext(strSiteUrl))
                {
                    EntityList<TestList1Item> Customers = ctx.GetList<TestList1Item>("testList1");
                    var query = from c in Customers.ToList()
                                select c;
                    foreach (var cust in query)
                    {
                        //cust.Animal.Id = 2;
                        cust.Animal.Title = "Dog";
                    }
                    ctx.SubmitChanges();
                }

3 comments:

  1. I tried this one but its giving me an exception Specified cast is not valid, any ideas why?

    ReplyDelete
  2. Please debug the code to see which line throw out that exception. Normally it is caused by inconsistent data type.

    ReplyDelete
  3. Actually, when I tried something similar, it seems to update the title of the target lookup item instead of updating the lookup reference of my source item...updating using ID doesn't work either.

    ReplyDelete