LINQ to SharePoint

Ratings:
(4)
Views: 0
Banner-Img
Share this blog:

LINQ

In SharePoint 2010 you now have the ability to use LINQ syntax to fetch items from your lists instead of using the "traditional" approach of CAML queries. (Including SPSiteDataQuery and SPQuery objects) LINQ or Language Integrated Query is a very useful language which reduces the complexity of accessing and integrating information that is not natively defined using OO technologies, with LINQ it adds native data querying capabilities to .NET languages which makes a developer's life really easy. Since it was launched, I started using it as it saves me a lot of time in coding my applications. LINQ adds a SQL-like syntax and vocabulary to each of the languages, which can be used to query data sources. But unlike other languages and query syntaxes which vary from one type of data source to another, LINQ can be used to query, in principle, any data source whatsoever. For this reason, developers may find that it is the only query syntax that they ever need to know. All that is necessary to make a data source accessible with LINQ is that someone creates a LINQ provider for the data source. A LINQ provider is an implementation of the System.Linq.IQueryable<T> and System.Linq.IQueryProviderinterfaces that are included with Microsoft .NET Framework (System.Core.dll). The implementing classes must be public in a managed code assembly. The primary job of the class that implements IQueryProvider is to translate LINQ queries into the language of the data source, such as SQL or XQuery, then call the data source’s application to execute the query. The provider must also expose a gateway class whose instances can communicate with the data source and outputIEnumerable<T> objects. For example, the gateway class for LINQ to SQL is DataContext and the gateway class for LINQ to XML is XDocument. The gateway class must implement System.Linq.IQueryable<T> or have a child property that does so or has a method that returns a type that implements System.Linq.IQueryable<T>. For example,DataContext has a GetTable() method that returns a Table<TEntity> type that implements System.Linq.IQueryable<T>. The latter interface, in turn, has a property of type IQueryProvider. (The gateway class can also directly implementIQueryProvider.) It is objects of type Table<TEntity> that are queried. In many cases, a LINQ Provider cannot be used by a .NET solution developer unless the developer creates a set of entity classes to represent the subordinate entities in the data source, such as the particular tables of a particular SQL database. Frequently, a lot of such classes must be created (e.g., a database with three dozen tables), so the developer of a LINQ provider will typically include a code generation tool to automate the process of creating these entity classes. In this article, you are able to learn how you can get started using LINQ queries in SharePoint, also known as LINQ to SharePoint. In order to work with LINQ in SharePoint 2010, we need to use a tool called SPMetal.exe which resides in the14bin folder. This tool is used to generate some entity classes which Visual Studio 2010 can use to get IntelliSense, and allows for LINQ-based queries to be performed on your lists. Noteworthy: how to write CAML queries. LINQ queries can be used in server code. To query from a client application, use SharePoint's support for ADO.NET Data Services. The gateway class for the LINQ to SharePoint provider is Microsoft.SharePoint.Linq.DataContext which represents the data of a SharePoint Foundation Web site. It is parallel in use and function to the System.Data.Linq.DataContext class in the LINQ to SQL provider. Just as the latter class has a GetTable() method that returns a Table<TEntity> object that implements System.Linq.IQueryable<T>, so too, the Microsoft.SharePoint.Linq.DataContext class has a GetList<T>method that returns an EntityList<TEntity> class that implements System.Linq.IQueryable<T>. It is objects of type entityList<TEntity> that are queried.

Desired to gain proficiency on SharePoint?  Explore the blog post on the "SharePoint Training" course to become a pro in SharePoint.

 

Visual Studio 2010 – Let’s create a sample Web Part that utilizes LINQ to SharePoint

In this sample, I will create a simple Web Part that will use LINQ to SharePoint syntax to fetch some information from the Announcements list. A basic sample I use in my training classes as well, and should be fairly easy to grasp!  

  1. Create a new project (I’m going to create a new Visual Web Part project)
  2. Import your Data Context-file by choosing yourProject -> Add -> Existing Item:
  3. Specify your file (mine is called MyEntities.cs):
  4. Make sure it’s properly placed in your project structure – then we’re good to go:

42

  Alright – that’s easy enough. Thus far we have created an entity file using SPMetal.exe and now we have successfully imported it into our project. Add proper references Now in order to use LINQ to SharePoint, you also need to reference the Microsoft.SharePoint.Linq assembly. Point to references, right-click, and choose "Add Reference" and select Microsoft. SharePoint.Linq.dll file: In your code, reference the assemblies: 43

What you should’ve done up until now is this:

  1. Generate your entities using the SPMetal.exe tool
  2. Reference the newly created file from your SharePoint project
  3. Make sure you’re using the proper references for System. Linq and Microsoft.SharePoint.Linq

In this example, we will have a Visual Web Part that will use LINQ to SharePoint to fetch all Announcements from my Announcement-list and work with those results. 44

IntelliSense!

While you code your queries using LINQ to SharePoint, you will now have access to IntelliSense, which you did not have with CAML queries:

45

Very easy to get started with LINQ to SharePoint, and all you really need to know is to start using the SPMetal tool to generate your entity classes and hooked up with Visual Studio to start coding. You can try the following operations: Read, Insert, Update, and Delete using LINQ to SharePoint.

Selecting an Item

Now we are trying to select the managers with the country as the USA:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext("http://appes-pc"))

{ var result = context.Manager.Where(m => m.Country == "USA");

foreach (ManagerItem manager in result) { Console.WriteLine(manager.Name); } }

Note: You can use LINQ or Lambda Expression to do the query. In the above example, I have used Lambda. On executing the application you can see the following results.

Inserting an Item

For inserting a new item into the Manager list, use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext("http://appes-pc"))

{ ManagerItem manager = new ManagerItem();

manager.Name = "New Manager";

manager.Address = "New Address";

manager.Country = "New Country"; context.Manager.InsertOnSubmit(manager);

context.SubmitChanges(); }

After executing the application, open the Manager list inside SharePoint as shown below:

46

For an in-depth understanding of SharePoint click on:

 

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox