User Tools

Site Tools



At first use the tool SPMetal to create the SPLinqDataContext class:

Location: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN
Syntax: SPMetal /web:http://MyServer /namespace:MyNamespace /code:MyFile.cs
Example: SPMetal /web:http://leszek-pc /namespace:WBS.SharePointTest.LinqData /code:SPLinq.cs

Next, create a container (a GridView) to show the results of your LINQ query:

<SharePoint:SPGridView id="GridView1" AutoGenerateColumns="false" runat="server">
<HeaderStyle HorizontalAlign="Left" />
    <SharePoint:SPBoundField DataField="LinkTitle" HeaderText="Name"></SharePoint:SPBoundField>
    <asp:TemplateField  HeaderText="Url">
        <asp:HyperLink ID="hypUrl" NavigateUrl='<%# Eval("LinkUrl")%>' 
            Text='<%# Eval("LinkUrl")%>' runat="server" />

Write your LINQ query. The query retrieves data from a custom list “Search Engines” that was created using the built-in Links template:

using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Linq;
using WBS.SharePointTest.LinqData; // the namespace provided in SPMetal
namespace WBS.SharePointTest
    public partial class TestPage : LayoutsPageBase
        protected void Page_Load(object sender, EventArgs e)
            var dc = new SPLinqDataContext(SPContext.Current.Web.Url);
            var links = dc.GetList<Link>("Search Engines"); // list type: Link, list name: Search Engines
            var query = from link in links
                        select new { 
                            LinkId = link.Id.ToString(),
                            LinkTitle = link.URL.Substring(link.URL.IndexOf(',') + 1).Trim(),
                            LinkUrl = link.URL.Substring(0, link.URL.IndexOf(','))
            GridView1.DataSource = query;

This is a sample screenshot:


Another example (ddlTemplates is a drop-down list):

private void PopulateTemplates()
    var dc = new SPLinqDataContext(SPContext.Current.Site.Url);
    EntityList<CustomTemplatesItem> allTemplates = 
    var filteredTemplates = 
        from CustomTemplatesItem template in allTemplates
        where template.Available == true && 
            (template.TemplateType == "List" || template.TemplateType == "Library")
        orderby template.Title
        select new
            TemplateName = (template.TemplateType == "List" ? "0" : "1") + "-" + template.Title, 
            TemplateTitle = template.Title
    ddlTemplates.DataValueField = "TemplateName";
    ddlTemplates.DataTextField = "TemplateTitle";
    ddlTemplates.DataSource = filteredTemplates;
notes/sharepoint2010/linq.txt · Last modified: 2020/08/26 (external edit)