Friday, July 15, 2011

LinQ to SharePoint examples

Namespaces to refer in Visual studio for using LinQ

using System.Linq;
using Microsoft.SharePoint.Linq;
using System.Collections.Generic;

Generate Entity classes using SPMetal
Run the following command to generate it
spmetal /web:http:// /code:

Creating a Join between two list UserAccounts and Invoices.
List UserAccounts have Account, Name
List Invoices have Account, Amount, Paid

//First refer the Datacontext class
XDataContext a = new XDataContext(SPContext.Current.Web.Url);

//Refere the Lists and create entityLists out of them

EntityList Invoices = a.GetList("Invoices") ;
EntityList UserAccounts = a.GetList("UserAccounts");

//need to do a join from the two lists and bring them together.
//use the ToList() on the list in the from to avoid getting errors due to inefficient CAML queries. with this method it retrives data from the list instantaniously.

var query=
(from u in UserAccounts.ToList()
join i in Invoices on u.Account equals i.Account
where int.Parse(u.Account.ToString()) > 1001 && int.Parse(u.Title.ToString()) < 10010
select new { u.Name, u.Account, i.Amount, i.Paid }) ;

//make this as the datasource.GridView1.DataSource = query;

Inserting in Lists using LinQ

XDataContext a = new XDataContext(SPContext.Current.Web.Url);

EntityList Invoices = a.GetList("Invoices");

int count = 0;
//get the count of the records
count =
(from x in Invoices
select x).Count();

List ic = new List();

if (count == 0)
    //insert 5K records
    for (int i = 0; i < 300; i++)
       //create records and store them in a system.collection.generic.list collection
       InvoicesItem inv = new InvoicesItem() { Account = "100" + i.ToString(), Amount = 100 + i, Paid = check(i) };

//insert all of them in shot

//here is the check function that is being used
private Boolean check(int i)

if (i % 2 == 0)
return false;
return true;

1 comment: