SharePoint Entity Framework是一个用来在SharePoint列表项和自定义实体类之间做双向转换的开源类库(项目主页:http://spentity.codeplex.com)。您只需要编写简单的实体类,就可以随时将SharePoint列表项的字段值读取到实体类的对应属性中,也可以随时将实体类的属性值写入到SharePoint ListItem的对应字段中,并且在大多数情况下,您无需关心转换逻辑。SharePoint Entity Framework可以极大的提升您的编码效率,也能帮助您编写出更加健壮的代码。
支持的类型
SharePoint Entity Framework支持绝大部分的SharePoint内置字段类型以及它们可能对应的CLR类型。所支持的所有类型如下表所示:
SharePoint字段类型 | CLR类型 |
单行文本 | StringGuid, Guid? |
多行文本 | string |
选项 | 自定义枚及其可空形式 |
数字 | int, int?double, double? |
货币 | decimal, decimal? |
时间和日期 | DateTime, DateTime? |
是/否 | bool, bool? |
超链接或图片 | UriString自定义类型 |
用户或用户组 | SPUser, SPUser[], List<SPUser>int, int[], List<int>string, string[], List<string>自定义类型及其集合形式 |
查阅项 | int, int[], List<int>string, string[], List<string>自定义类型及其集合形式 |
基类及其成员
SharePoint Entity Framework规定所有实体类都必须直接或间接地从基类Entity(位于WindStyle.SPEntity命名空间)派生而来。
Entity提供的默认属性如下表所示:
属性 | 类型 | 备注 |
SPListItemId | int | 对应列表项的标识符 |
SPListItemUniqueId | Guid | 对应列表项的唯一标识符 |
SPParentListId | Guid | 对应列表项的父列表唯一标识符 |
SPParentWebId | Guid | 对应列表项的父网站唯一标识符 |
SPParentSiteId | Guid | 对应列表项的父网站集唯一标识符 |
Title | string | 对应列表项的标题 |
Entity提供的默认方法如下表所示:
方法 | 返回值 | 备注 |
Read(SPListItem) | void | 将SharePoint列表项读入到实体 |
Write(SPListItem) | void | 将实体写入到SharePoint列表项 |
编写简单实体类
下面来编写一个简单的实体类:
using
WindStyle.SPEntity;
using
WindStyle.SPEntity.Attributes;
public
class
SampleEntity : Entity
{
[Field(
"Field1"
)]
public
int
Property1 {
get
;
set
; }
[Field(
"Field2"
)]
public
string
Property2 {
get
;
set
; }
}
|
SampleEntity类包含两个属性Property1和Property2,它们都被FieldAttribute修饰。在对实体类进行转换操作时,SharePoint Entity Framework会根据FieldAttribute中指定的字段内部名称来在列表项中查找对应的字段。
转换
将SharePoint列表项读入到实体的代码如下所示:
SPListItem item = DoSomethingToGetListItem();
Sample entity =
new
SampleEntity();
entity.Read(item);
|
实体的属性值发生变化后,如果需要写回到SharePoint列表项,则需要调用实体的Write方法。代码如下所示:
entity.Property1++;
entity.Write(item);
item.Update();
|
批量转换
在进行SharePoint开发时,我们常常会和SPListItemCollection打交道,SharePoint Entity Framework内置的Utilities类提供了两个实用方法来帮助我们进行批量转换:
方法 | 返回值 | 描述 |
AsEnumerable(SPListItemCollection) | IEnumerable<SPListItem> | 将SPListItemCollection转换为IEnumerable<SPListItem> |
Convert<T>(IEnumerable<SPListItem>, SPRegionalSettings) | IEnumerable<T> | 将IEnumerable<SPListItem>转换为指定类型的IEnumerable<T> |
为了简化调用,这两个方法都已经实现为扩展方法。下面是批量转换的示例代码:
SPListItemCollection items = DoSomethingToGetListItems();
SampleEntity[] entities = items.AsEnumerable().Convert<SampleEntity>().ToArray();
|
SharePoint Entity Framework旨在帮助开发人员快速地在实体类和SharePoint列表项之间做转换。为此,它提供了对绝大多数常见类型的支持,并尽可能地将API设计地简单友好。
对于简单的应用场景,您需要编写的代码可能并不会比上面的示例多多少。而对于复杂应用场景,SharePoint Entity Framework也提供了相应的扩展机制,更多技巧请阅读后续文章。
下一节:
SharePoint Entity Framework 2 – Attributes
转载至:http://coding.windstyle.cn/sharepoint-entity-framework-1-introduction/