我在SharePoint上有一个列表,我正在尝试为此列表加载字段,如下所示:
var lists = context.Web.Lists;
context.Load(lists, n => n.Include(x => x.Title,
x => x.Fields.Include(
z => z.Title,
z => z.InternalName,
z => z.TypeDisplayName)));
context.ExecuteQuery();
我在代码中经常使用的代码的以下部分,与其他列表一起使用时:
x => x.Fields.Include(
z => z.Title,
z => z.InternalName,
z => z.TypeDisplayName)
我想知道是否有一种方法可以简化如何在我的代码中插入这个.Include
语句(以便以后我将不得不添加更多属性,我不必重写所有我的代码无处不在,但只在一个地方。)
我试图创建自定义LINQ扩展,但它失败了,因为它可能期待Expression<Func<T,Y>>
(我猜)。
对此事的任何帮助都不胜感激!
答案 0 :(得分:1)
由于Load
方法需要Expression<Func<T, object>>
,而lists
大概是IQueryable<Something>
,因此您可以使用以下内容:
public static Expression<Func<IQueryable<Something>, Object>> IncludeCommonFields()
{
// since the method returns an Expression, this will actually
// get compiled to an expression tree
return input => input.Fields.Include(z => z.Title,
z => z.InternalName,
z => z.TypeDisplayName);
}
评估函数应该创建表达式树的新实例:
var lists = context.Web.Lists;
context.Load(lists, n => n.Include(x => x.Title,
IncludeCommonFields());
context.ExecuteQuery();
如果经常调用它,您也可以选择仅实例化一次:
static readonly Expression<Func<IQueryable<Something>, Object>> _commonIncludes
= input => input.Fields.Include(z => z.Title,
z => z.InternalName,
z => z.TypeDisplayName);
context.Load(lists, n => n.Include(x => x.Title,
_commonIncludes);