Tuesday, June 5, 2012

SharePoint 2010 - Linq

If you want to use Linq in SharePoint, you have to generate class using SPMetal utility.
You have to provide some parameters to generate class file like web, namespace, class etc.



This command will generate class file for you and you have to attach to you project file.

You have to add reference from 14/ISAPI folder for Sharepoint.Linq dll.

Here is the simple code snippet to get List items.


using System.Linq;
using Microsoft.SharePoint.Linq;
using SP2010.Demo;


namespace SP2010.Demo.LinqWebPart
{
    [ToolboxItemAttribute(false)]
    public class LinqWebPart : WebPart
    {
        protected override void CreateChildControls()
        {
            using (var ctx = new LinqDemoDataContext(SPContext.Current.Web.Url))
            {
                var parentList = from pl in ctx.ParentList
                                 select new {pl.CustomerID,pl.Name };
                foreach(var p in parentList)
                {
                    Controls.Add(new LiteralControl(string.Format("{0},{1}
",p.CustomerID,p.Name)));
                }

            }
        }
    }
}






No comments:

Post a Comment