SharePoint 2010 – LINQ and SPMetal

linq

Introduction

In this article we explore some advanced programming areas:

  • LINQ to SharePoint
  • SPMetal

LINQ to SharePoint is a new feature of SharePoint 2010. LINQ stands for Language Integrated Query which is a part of .NET. The aim of LINQ is to support different data sources using the same Typed Query Syntax. Presently it supports Objects, Datasets, SQL, Entities, XML, etc.

Why do we need LINQ?

You might have noted that the previous List Programming examples did not use proper column name access. LINQ allows us to access the List in a Typed manner.  Adding more clarity we can access the list items based on the column names which we usually do with databases.

Example:

 Collapse | Copy Code
var result = from c in Citizen where c.Name == “John” select c;

What is SPMetal?

As we will be creating custom lists having custom column names, we need to generate the Entity Model. SPMetal.exeis the tool which helps in generating Model classes. Although we can create Model classes manually, it will be a tedious job and error prone. Using SPMetal would be the right approach to model classes.

Activities

Following are the activities performed in this article:

  1. Manager List Creation
  2. Entity Creation
  3. Read using LINQ
  4. Insert Entity
  5. Update Entity
  6. Delete Entity

Experimenting with LINQ and SPMetal

To start with, create a custom list inheriting from Custom List and name it Manager. Add the following custom columns and data:

Generating the Entity Models

Now we can generate the Entity Model for the above List. You can get SPMetal.exe inside the following folder:C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN.

Open a command prompt and go to the specified folder:

Now run the following command:

 Collapse | Copy Code
SPMetal.exe /web:http://YOURSITE /code:SiteEntities.cs

Wait for a while and you will be ready with the new file. Open the file SiteEntities and you can see the Manager class is contained inside.

Create Application

Create a new SharePoint > 2010 > Console Application (targeting the .NET 3.5 framework) and add the SiteEntities.csfile into it.

Add a reference to the following assembly:

You can try the following operations: Read, Insert, Update, Delete using LINQ to SharePoint.

Selecting an Item

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

 Collapse | Copy Code
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:

 Collapse | Copy 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:

Updating an Item

For updating an item inside SharePoint, use the following code:

 Collapse | Copy Code
using (SiteEntitiesDataContext context = new SiteEntitiesDataContext("http://appes-pc"))
{
    ManagerItem manager = context.Manager.Where(m =>  
                          string.IsNullOrEmpty(m.Title)).FirstOrDefault();
    if (manager != null)
        manager.Title = "New Title";

    context.SubmitChanges();
}

You can see the updated entity inside SharePoint:

Deleting an Item

For deleting an item inside SharePoint use the following code:

 Collapse | Copy Code
using (SiteEntitiesDataContext context = new SiteEntitiesDataContext("http://appes-pc"))
{
    ManagerItem manager = context.Manager.Where(m => m.Title.Length > 3).FirstOrDefault();
    if (manager != null)
        context.Manager.DeleteOnSubmit(manager);

    context.SubmitChanges();
}

You can see that the item is deleted inside SharePoint:

This concludes our Read, Insert, Update, Delete operations using LINQ to SharePoint. Hope the topics are understood by the reader.

Introduccion a LinQ con C#

Intruduccion general

LinQ es una metodologia de consulta de datos que se caracteriza por unificar cualquier origen de datos y obtener los resultados deseados usando un mismo lenguaje de consulta. LinQ utiliza objetos pero puede utilizarse para consultar datos de varios origenes de datos; ado.net, base de datos sql, datos xml, etc.

Un ejemplo sencillo

A continuación se muestra una clase sencilla que realiza una consulta LinQ a partir de un array de enteros. Este ejemplo muestra los tres componentes que conforman una sentencia LinQ;  Origenes de Datos, Creacion de una consulta y ejecuciòn de una consulta.

class IntroToLINQ
{
    static void Main()
    {
        // The Three Parts of a LINQ Query:
        //  1. Data source.
        int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

        // 2. Query creation.
        // numQuery is an IEnumerable<int>
        var numQuery =
            from num in numbers
            where (num % 2) == 0
            select num;

        // 3. Query execution.
        foreach (int num in numQuery)
        {
            Console.Write("{0,1} ", num);
        }
    }
}

A continuaciòn detallaremos las tres partes que conforman una consulta LinQ:

El Origen de Datos:

Un origen de datos LINQ es cualquier objeto que admite la interfaz genérica IEnumerable<T> o una interfaz que herede de ella.

La creaciòn de una consulta:

La consulta especifica qué información se va a recuperar de uno o varios orígenes de datos.Opcionalmente, una consulta también especifica cómo debería ordenarse, agruparse y darse forma a esa información antes de ser devuelta.Una consulta se almacena en una variable de consulta y se inicializa con una expresión de consulta.Para simplificar la escritura de consultas, C# incluye nueva sintaxis de consulta.

La ejecuciòn de una consulta:

Como se ha mencionado previamente, la variable de consulta sólo almacena los comandos de la consulta.La ejecución real de la consulta se aplaza hasta que se procese una iteración en la variable de consulta, en una instrucción foreach.Este concepto se conoce como ejecución diferida y se muestra en el ejemplo siguiente:

//  Query execution.
foreach (int num in numQuery)
{
    Console.Write("{0,1} ", num);
}

La instrucción foreach es también donde se recuperan los resultados de la consulta.Por ejemplo, en la consulta anterior, la variable de iteración num contiene cada valor (de uno en uno) en la secuencia devuelta.

Dado que la propia variable de consulta nunca contiene los resultados de la consulta, se puede ejecutar tantas veces como se desee.Por ejemplo, puede que una aplicación independiente actualice continuamente una base de datos.En su aplicación, podría crear una consulta que recuperase los datos más recientes, y podría ejecutarla repetidamente cada cierto tiempo para recuperar cada vez resultados diferentes.

Happy Programming .NET