Learning goals in this section: reading SharePoint list data with LINQ and presenting the data through SPGridView
- To build a LINQ to SharePoint proxy class
Navigate to "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\bin" from the command line
- Enter the following code to generate the proxy class
Spmetal.exe/web:http://intranet.contoso.com/namespace:jonny.visualwebpart1/code:splinq.cs
Note:/web for your site,/namespace generates the namespace of the class, preferably the same as the project namespace you are referencing,/code the generated class name. The default generated class is the same directory as Spmetal.exe
- Referencing proxy classes in projects
Select the proxy class we just generated by right-clicking the item--new--Existing item--
- Add Microsoft.SharePoint.Linq.dll to the project
Browse (C:\Program files\common files\microsoft Shared\Web Server Extensions\14\isapi) by right-clicking items--Add references
- reading list data from LINQ to SharePoint
In the empty Web Part created in the previous section, add SPGridView
<sharepoint:spgridview id="SPGridView"runat="Server"autogeneratecolumns="false"> " Left"Forecolor="Navy"Font-bold="true"/> <Columns> <sharepoint:spboundfield datafield="Title"headertext="Title"></SharePoint:SPBoundField> <sharepoint:spboundfield datafield="JobTitle"headertext="JobTitle"></SharePoint:SPBoundField> <sharepoint:spboundfield datafield="Projecttitle"headertext="Projecttitle"></SharePoint:SPBoundField> <sharepoint:spboundfield datafield="DueDate"headertext="DueDate"></SharePoint:SPBoundField> </Columns> </SharePoint:SPGridView>
After adding the code
- Adding code to read list in the Page_Load event
varDC =NewSplinqdatacontext (SPCONTEXT.CURRENT.WEB.URL);varEmployees = DC. Getlist<employeesitem> ("Employees"); varEmpquery = fromEmpinchEmployeeswhereEmp. Project.duedate < DateTime.Now.AddMonths (6)Select New{emp. Title, EMP. JobTitle, Projecttitle = emp. Project.title, DueDate =EMP. Project.DueDate.Value.ToShortDateString ()}; Spgridview.datasource=empquery; Spgridview.databind ();
Note: You need to have a list of "Employees" and "project" in the site before the code runs, and the fields with 2 lookup types in ' Employees ' are from ' project ' (title,duedate)
Using the LINQ to SharePoint steps
- To generate a proxy class from a command
- To add a proxy class to a project
- reading data Using LINQ
- Using controls to show data
Linq to SharePoint Advantage disadvantage
- With strong typing, errors can be found at compile time (advantage)
- If the list in the site has been restructured, the proxy class needs to be rebuilt, which is cumbersome (disadvantage)
- Low query efficiency (disadvantage) for large amounts of data
SharePoint QuickStart (2) WebPart