Search This Blog

Sunday, December 7, 2014

LINQ In Sharepoint

         
What is LINQ and why it’s useful in LINQ?

LINQ is Language integrated Query Language. It’s part of .Net framework, you can easily integrate this with SharePoint 2010. It’s used to Query on Data sources such as Object, Datasets, SQL, XML and other entities. LINQ provide access to sharepoint in TYPED Manner, you can easily access List columns name as property. As syntax is same as it is for .net development.
var items = from s in DataContext.Students
           select s;


SPMetal
SPMetal is tool provided by sharepoint , used to created entity model for sharepoint site objects. You can write these classes manually as well, but its very time consuming task. It will create partial class at specified location, you can simply add these classes in your project.
Simple CRUD operation using LINQ for SharePoint List
Step 1: Create List
Create a simple list in sharepoint site .i have created Custom List with the name of students(Title, firstname,lastname, Country).
Step 2:  Generate Entity model.
Open command line -> start -> type cmd in search box -> open Command Line.
Type CD C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN
This is path for SPMetal.exe
Now in command line type   SPMetal.exe /web: http://sp2010-sana /code: C:/MyEntities.cs
Note : just put your web url instead of  http://sp2010-sana
It will create entities classes for you. Go to given path in command to verify.
Step 3: Create Visual WebPart.
Open Visual studio 2010 and Create new sharepoint 2010 visual webpart project,
File -> New -> Project -> Sharepoint - >2010  -> Visual web part . Give its appropriate name and location and press OK.
 Visual webpart work as form solution so next you have to verify your site url and press ok.
 Visual studio load its project structure.
Now you have to add reference for LINQ.
Right Click on Project (Solution Explorer)  -> Add Reference -> Select Microsoft.Sharepoint.LINQ
In code Behind of Webpart, add following Namespaces
using System.Linq;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;


In visual web part  you can simple trag and drop control to perform your operation.
After creating form design you have to move in code behind . (.CS file of webpart)
I have  written these four methods to perform CRUD Operation
#region CRUD Operation using LINQ
        /// <summary>
        /// Delete the student
        /// </summary>
        /// <param name="objTitle"></param>
        public void DeleteStudent(string objTitle)
        {
            try
            {
                using (MyEntitiesDataContext dc = newMyEntitiesDataContext(SPContext.Current.Site.Url))
                {
                    EntityList<StudentsItem> listItems = dc.GetList<StudentsItem>("Students");
                    var updateobj = (from c in listItems
                                     where c.Firstname == objTitle
                                     select c).First();
                        dc.Students.DeleteOnSubmit(updateobj);
                    //Submit the changes
                    dc.SubmitChanges();

                }

            }
            catch (Exception ex)
            {

                Response.Write(ex.Message);
            }
        }

        /// <summary>
        /// Insert Student
        /// </summary>
        public void InsertStudent()
        {
            try
            {

                using (MyEntitiesDataContext dc = newMyEntitiesDataContext("http://sp2010-sana/"))
                {
                    EntityList<StudentsItem> listItems = dc.GetList<StudentsItem>("Students");
                    StudentsItem objnew = new StudentsItem()
                    {
                        Firstname = txtFname.Text.Trim(),
                        Lastname = txtLname.Text.Trim(),

                        Country = Country.USA,
                        Title = txtTitle.Text.Trim()
                    };// Insert the new list item to the list
      dc.Students.InsertOnSubmit(objnew);
                    dc.SubmitChanges();
                }
            }
           
            catch (Exception ex)
            {
               
                throw;
            }
        }
        /// <summary>
        /// Update items
        /// </summary>
        /// <param name="objTitle"> title for the Item</param>
        public void UpdateStudent(string objTitle)
        {
            try
            {

                using (MyEntitiesDataContext dc = newMyEntitiesDataContext("http://sp2010-sana/"))
                {
                    EntityList<StudentsItem> listItems = dc.GetList<StudentsItem>("Students");
                    StudentsItem updateobj = (from c in listItems
                                    where c.Id == 4
                                    select c).First();
                                  updateobj.Lastname = "Item2";
                    updateobj.Firstname = "Item2";
                    txtLname.Text = updateobj.Id.ToString();
                
                    dc.Students.InsertOnSubmit(updateobj);
                    dc.SubmitChanges();
}

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message + "</br>");
            }
        }


        #endregion


I have Created one Grid View to Show all the students. So in in Page Load I have just added data source to Gridview.  You can see one more method name as Register Events() , I have used it to register all events (such as I am using 2 buttons (btnsave and btndelete))
  protected void Page_Load(object sender, EventArgs e)
        {
            using (MyEntitiesDataContext dc = newMyEntitiesDataContext(SPContext.Current.Site.Url))
            {

                var items = from s in dc.Students
                            select s;

                GridView1.DataSource = items;
                GridView1.DataBind();
               
            }

            RegisterEvents();
        }

        
        public void RegisterEvents()
        {
            btnSave.Click += new EventHandler(btnSave_Click);

            btnDelete.Click += new EventHandler(btnDelete_Click);

No comments:

Post a Comment