我正在尝试使用ODataQueryOptions在自定义DAL中实现一些OData功能。
我的DAL使用设计时生成的类型化数据表。通过拦截ODataQueryOptions的SelectExpand属性,我可以让我们的DAL只加载所需的列。
我如何只返回所需的数据。
我目前正在将数据从我们的类型数据表转换为ListOf一些类型化的数据传输对象,但最后会从不需要的列中获得大量空数据。
我觉得我应该能够做一些LINQ查询,直接从键入的数据表中选择我需要的列,直接使用类型化的DTO。这可能吗?
答案 0 :(得分:3)
您需要执行与SelectExpandQueryOption.ApplyTo相同的操作。
1)优化对后端的查询。而不是从数据库中获取整个实体,只获取客户端要求的属性并将结果包装在IEdmEntityObject中。将集合作为EdmEntityObjectCollection返回。此步骤是可选的。您可以选择忽略此步骤并返回IQueryable并仍然可以使$ select工作。
2)告诉OData格式化程序仅序列化请求的字段。这可以通过使用扩展方法Request.SetSelectExpandClause
将SelectExpandClause填充到Request对象上来完成。
public class CustomersController : ODataController
{
public IEnumerable<Customer> Get(ODataQueryOptions<Customer> query)
{
Customer[] customers = new[] { new Customer { ID = 42, Name = "Raghu" } };
// Apply query
var result = customers;
// set the SelectExpandClause on the request to hint the odata formatter to
// select/expand only the fields mentioned in the SelectExpandClause.
if (query.SelectExpand != null)
{
Request.SetSelectExpandClause(query.SelectExpand.SelectExpandClause);
}
return result;
}
}