標籤:style blog http color io os ar 使用 for
本節學習目標:用Linq讀取Sharepoint List資料,並通過SPGridView展示資料
通過命令列定位到“c:\program files\common files\microsoft shared\web server extensions\14\bin”
spmetal.exe /web:http://intranet.contoso.com /namespace:Jonny.VisualWebPart1 /code:SPLinq.cs
備忘:/web為你的網站,/namespace產生類的命名空間,最好和你要引用的項目命名空間一致,/code產生的類名。預設產生的類與spmetal.exe同一個目錄
通過右鍵項目-->新增-->現有項-->選擇我們剛剛產生的代理類
- 項目中添加Microsoft.SharePoint.Linq.dll
通過右鍵項目-->添加引用-->瀏覽(C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI)
- 通過Linq to sharepoint讀取list資料
在上一節建立的空web part中,添加SPGridView
<SharePoint:SPGridView id="spGridView" runat="server" AutoGenerateColumns="false"> <HeaderStyle HorizontalAlign="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>
添加代碼後的
var dc = new SPLinqDataContext(SPContext.Current.Web.Url); var Employees = dc.GetList<EmployeesItem>("Employees"); var empQuery = from emp in Employeeswhere emp.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();
備忘:代碼運行前需在網站中存在"Employees"和"Project"的List, 並且‘Employees‘中有2個LookUp類型的欄位是來自於‘Project‘(Title,DueDate)
使用Linq to sharepoint步驟
- 通過命令組建代理程式類
- 將代理類添加到項目
- 使用Linq讀取資料
- 使用控制項展示資料
Linq to sharepoint優劣勢
- 採用強型別,在編譯時間即可發現錯誤(優勢)
- 如果網站中的List做了結構調整,代理類需要重建,很繁瑣(劣勢)
- 對於大量資料的查詢效率低(劣勢)
SharePoint快速入門(2)之WebPart