Linq to sharepoint
一、Linq to SharePoint
首先Linq to SharePoint編程語言 C# 和 Microsoft Visual Basic .NET 的一個功能,編譯器是 Visual Studio 附帶的。
Linq to SharePoint是LINQ家族中的一員,如果使用過例如Linq to SQL的話,就會發現Linq to SharePoint與其有很多相同之處。
如Linq to SQL中有DataContext類,用來打開數據庫連接並進行操作。Linq to SharePoint也有DataContext,同樣用來對SharePoint中的數據進行操作。
二、SPMetal
使用Linq to SharePoint 很重要的一步是生成Entity類,也就是所說的SharePoint實體類,用來映射到SharePoint對應的文檔庫、列表等等。手動創建實體類,是一件很痛苦的事情,復雜且易錯,幸好有SPMetal工具來自動生成。當然,這個工具也有一些限制,如自定義字段不會生成對應實體,文檔庫附件不會生成。如果有這樣的需求,那只能使用擴展對象關系映射,這一點上本人也涉獵較淺,就不做贅述,還是直接使用微軟提供的工具吧。接下來是SPMetal的使用方法:
1、使用默認代碼生成規則
如果沒有特殊要求,默認規則就可以滿足程序的要求。
步驟一、打開命令行CMD
步驟二、cd(空格)
步驟三、運行命令:
SPMetal /web:http://yoursite /code:類名.cs /language:csharp回車Warning:All content type for list 列名 were excluded.
SPMetal /web:http:
//我們的SharePoint站點:端口 /code:SiteEntities.cs
註意:/號前空格
還有一些其他的參數,可以設置生成代碼的namespace、serializetion,可以參考MSDN文檔
增,刪,改操作
下面以此List為對象進行相應的增,刪,改操作1、添加操作
EntitiesDataContext edc = new EntitiesDataContext(SPContext.Current.Web.Url);PersonsItem installitem = new PersonsItem();
installitem.Title = “張三”;
edc.Persons.InsertOnSubmit(installitem);
edc.SubmitChanges();
2、修改操作
EntitiesDataContext edc=new EntitiesDataContext(SPContext.Current.Web.Url);
var mypersons = edc.Persons;//列名
var updateitem = (from item in mypersons
where item.Title == "張三"
select item).First();
updateitem.Title = "李四";
edc.SubmitChanges();
3、刪除操作
EntitiesDataContext edc=new EntitiesDataContext(SPContext.Current.Web.Url);var mypersons = edc.Persons;//列名
var deleteitem = (from item in mypersons
where item.Title == "張三"
select item).First();
updateitem.Title = "李四";
edc.SubmitChanges(); // Deleting the list item
mypersons.DeleteOnSubmit(delItem); // Submit the changes
edc.SubmitChanges();
Linq to sharepoint