【发布时间】:2014-05-23 01:10:55
【问题描述】:
我在允许 OData 查询的 Asp.Net Web Api 应用程序中有一个 ODataController。我只允许读取,不允许更新。我没有直接公开数据模型,而是创建了一组 DTO。 DTO 上的属性名称不一定与 EF 模型上的属性匹配。当我尝试对 EF 模型使用 OData 查询时,这会导致问题。我查看了 StackOverflow 上围绕这个主题的其他帖子,但似乎都没有解决这个问题。
这是我现在拥有的:
public IQueryable<Customer> GetCustomer(ODataQueryOptions<Customer> query)
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
builder.EntitySet<RECORD>("Records");
builder.Namespace = "MyDataService.Models";
var opts = new ODataQueryOptions<RECORD>(new ODataQueryContext(builder.GetEdmModel(), typeof(RECORD)), this.ActionContext.Request);
var records = (IQueryable<RECORD>)opts.ApplyTo(db.RECORDS);
return ConvertToCustomerList(records);
}
在我引用选择或过滤器中的特定字段之前,此方法有效。一旦我在 OData 查询中引用了一个字段,我就会得到一个 ODataException,例如 - Could not find a property named 'LastName' on type 'MyDataService.Models.RECORD。这是因为 EF 属性具有不同的命名约定。在这种情况下,它应该使用“LAST_NAME”。
看来我需要解析查询,然后用正确的名称替换字段引用。我发现 ODataUriParser 似乎可以对此有所帮助,但它并不像我希望的那样干净。
谁能给我一些解决这个问题的建议?有更好的方法吗?
【问题讨论】:
标签: entity-framework asp.net-web-api odata