OData Client生成重复Expand&Select语句的优化方法咨询
OData Client查询生成重复$expand参数的优化问题
问题说明
我使用如下OData模型:
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"> <edmx:DataServices> <Schema Namespace="ODataIssue.Controllers" xmlns="http://docs.oasis-open.org/odata/ns/edm"> <EntityType Name="Product"> <Key> <PropertyRef Name="Id" /> </Key> <Property Name="Id" Type="Edm.Int32" Nullable="false" /> <Property Name="Name" Type="Edm.String" Nullable="false" /> <Property Name="Description" Type="Edm.String" Nullable="false" /> </EntityType> <EntityType Name="Category"> <Key> <PropertyRef Name="Id" /> </Key> <Property Name="Id" Type="Edm.Int32" Nullable="false" /> <Property Name="Name" Type="Edm.String" Nullable="false" /> <Property Name="Description" Type="Edm.String" Nullable="false" /> <NavigationProperty Name="Products" Type="Collection(ODataIssue.Controllers.Product)" /> </EntityType> </Schema> <Schema Namespace="Default" xmlns="http://docs.oasis-open.org/odata/ns/edm"> <EntityContainer Name="Container"> <EntitySet Name="Products" EntityType="ODataIssue.Controllers.Product" /> <EntitySet Name="Categories" EntityType="ODataIssue.Controllers.Category"> <NavigationPropertyBinding Path="Products" Target="Products" /> </EntitySet> </EntityContainer> </Schema> </edmx:DataServices> </edmx:Edmx>
执行这段OData Client查询代码时:
var query = container.Categories.Select(c => new { c.Id, c.Name, Products = c.Products.Select(p => new { p.Name, p.Description } ) }); var list = query.ToList();
生成的请求URL会重复Products($select=部分:
http://localhost:5184/odata/Categories?$expand=Products($select=Name),Products($select=Description)&$select=Id,Name
想知道能不能生成规范的合并版URL:
http://localhost:5184/odata/Categories?$expand=Products($select=Name,Description)&$select=Id,Name
解决方法
可以通过以下几种方式实现:
调整查询写法,显式指定Expand规则
直接通过链式API同时定义Select和Expand逻辑,避免匿名类嵌套导致的参数拆分:var query = container.Categories .Select(c => new { c.Id, c.Name }) .Expand(c => c.Products.Select(p => new { p.Name, p.Description })); var list = query.ToList();使用字符串形式的Select/Expand语句
直接传入符合OData规范的字符串参数,精准控制生成的URL:var query = container.Categories .Select("Id,Name") .Expand("Products($select=Name,Description)"); var list = query.ToList();升级OData Client版本
早期版本的OData Client在处理嵌套匿名类的导航属性选择时,存在多字段拆分的bug。如果使用的是旧版本,升级到最新稳定版后,原生的查询写法可能就能自动生成合并后的规范URL。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

