Thursday, February 19, 2015

LINQ to SharePoint to work with CRUD operation

LINQ is the best to work on list and its operations and avoiding SPSite, SPList and SPListItem stuffs.

Add item in list with LINQ to SharePoint

using (EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ram:40705/sites/site1/"))
            {
                EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
                EmployeeItem newItem = new EmployeeItem()
                {
                    FirstName = "deepak",
                    Title = "desai",
                };
                emp.InsertOnSubmit(newItem);
                dc.SubmitChanges();
            }

Update item

EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext ("http://ram:40705/sites/site1/");
               
                    EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
                    var updatedResult = (from empToUpd in emp
                                         where empToUpd.FirstName == "Yagnesh"
                                         select empToUpd).First();

                    updatedResult.FirstName = "Yagnesh2";
                    updatedResult.Title = "Kotecha";

                    dc.SubmitChanges();

Delete item

using (EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ram:40705/sites/site1/"))
            {
                EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
                var result = (from empToDel in dc.Employee
                                  where empToDel.FirstName.StartsWith("c", +
                                  StringComparison.CurrentCultureIgnoreCase)
                                  select empToDel);
                emp.DeleteAllOnSubmit(result);
                dc.SubmitChanges();

            }

No comments:

Post a Comment