LINQ是一种有效且高效的查询数据的方法。使用SPMetal你可以为LINQ准备SharePoint列表。下面讲解如何准备你的列表,并创建使用LINQ的应用程序。
1. 打开命令行(管理员身份运行)。
2. 导航到c:\Program Files\Common Files\Microsoft Shared\web server extensions\14\bin,并输入下面命令(确保用你自己的服务器名代替)
spmetal.exe /web:http://<servername> /code:SPEntityModel.cs /language:csharp
3. SPMetal命令工具将创建C#文件SPEntityModel.cs,你可以用在应用程序中对SharePoint列表模型执行LINQ查询(SPMetal主要将站点内所有列表翻译为实体模型)。
4. 管理员身份打开VS。
5. 新建空白SharePoint项目MyFirstSPLinqProject,点击确定,部署为场解决方案,完成。
6. 右击项目添加现有项,找到创建的SPEntityModel.cs。
7. 右击项目添加新建项,选择Web Part,命名MySPLinqWebPart。点击添加。
8. 右击引用,选择添加引用。点击浏览导航到文件夹c:\Program Files\Common Files\Microsoft Shared\web server extensions\14\ISAPI.选择Microsoft.SharePoint.Linq.dll,点击确定。
更多精彩内容:http://www.bianceng.cn/web/sharepoint/
9. 右击MySPLinqWebPart.cs,查看代码。
10. 修改代码:
using System;using System.ComponentModel;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;using Microsoft.SharePoint.Linq;using System.Linq;namespace MyFirstSPLinqProject.MySPLinqWebPart{[ToolboxItemAttribute(false)]public class MySPLinqWebPart : WebPart{Label myLabel = new Label();ListBox listTitles = new ListBox();Button myButton = new Button();protected override void CreateChildControls(){myLabel.Text = 'Lists:';myButton.Text = 'Get Lists';this.Controls.Add(myLabel);this.Controls.Add(listTitles);this.Controls.Add(new LiteralControl('<br />'));this.Controls.Add(myButton);myButton.Click = new EventHandler(myButton_Click);}void myButton_Click(object sender, EventArgs e){//Be sure to update the server reference//below to point to your server.using (SPEntityModelDataContext dataContext =new SPEntityModelDataContext('http://smallville-pc:1528')){var salesInfo = from data in dataContext.Customersselect data;foreach (var salesItem in salesInfo){listTitles.Items.Add(salesItem.Title.ToString() ' | ' salesItem.CustomerType.ToString());}}}}}
11. 修改.webpart文件代码:
<?xml version='1.0' encoding='utf-8'?><webParts><webPart xmlns='http://schemas.microsoft.com/WebPart/v3'><metaData><type name='MyFirstSPLinqProject.MySPLinqWebPart.MySPLinqWebPart, $SharePoint.Project.AssemblyFullName$' /><importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage></metaData><data><properties><property name='Title' type='string'>Customer Types</property><property name='Description' type='string'>Web Part that lists customers and customer types (using SP LINQ).</property></properties></data></webPart></webParts>
12. 完成后,部署解决方案。
13. 添加此Web Part。
14. 点击Get Lists可以获得列表对应客户和类型。
本机截图:
PS:此文与之前的博文http://blog.csdn.net/crazygolf/article/details/30710779有关联,请先完成这个练习。
作者:csdn博客 张世辉
联系客服