假设我有代码优先模型:
public class FooBar
{
[Key]
public int Id {get;set;}
[MaxLength(254)]
public string Title {get;set;}
public string Description {get;set;}
}
和检索行数据的一些子集的方法:
public IQueryable<FooBar> GetDataQuery(bool includeTitle, bool includeDescription)
{
var query = ctx.FooBars.AsNoTracking().Where(Id > 123);
//how to inlcude/exclude???
return query;
}
问题是如何使用特定字段构建查询而无需对匿名类型进行硬编码?基本上,我想告诉SQL查询构建器构建具有指定字段的查询,而无需在客户端上对它进行后期过滤。因此,如果我排除描述-它不会通过电线发送。
另外,有这样的经验:
public IQueryable<FooBar> GetDataQuery(bool includeTitle, bool includeDescription)
{
var query = ctx.FooBars.AsNoTracking().Where(Id > 123);
query = query.Select(x=> new
{
Id = x.Id
Title = includeTitle ? x.Title : null,
Description = includeDescription ? x.Description : null,
})
.MapBackToFooBarsSomehow();//this will fail, I know, do not want to write boilerplate to hack this out, just imagine return type will be correctly retrieved
return query;
}
但这将通过有线方式传递includeTitle,includeDescription属性作为EXEC的SQL参数,并且与没有这种混乱情况的简单非条件匿名查询相比,在大多数情况下查询效率低下-但是编写匿名结构的所有可能排列都不是一种选择。
相关分类