开发环境
模型
public class Computer
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Disk> Disks { get; set; }
}
public class Disk
{
public int Id { get; set; }
public string Letter { get; set; }
public float Capacity { get; set; }
public int? ComputerId { get; set; }
public virtual Computer Computer { get; set; }
}
Dtos
public class ComputerDto
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<DiskDto> Disks { get; set; }
}
public class DiskDto
{
public string Letter { get; set; }
public float Capacity { get; set; }
}
EF核心上下文
public class ComputerContext : DbContext
{
public DbSet<Computer> Computers { get; set; }
public DbSet<Disk> Disks { get; set;}
public ComputerContext(DbContextOptions<ComputerContext> options)
: base(options)
{
}
}
OData EDM模型
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Computer>("Computers");
builder.EntitySet<Disk>("Disks");
builder.ComplexType<ComputerDto>();
builder.ComplexType<DiskDto>();
return builder.GetEdmModel();
}
ASP.NET核心控制器
[Route("api/[controller]")]
[ApiController]
public class ComputersController : ControllerBase
{
private readonly ComputerContext context;
public ComputersController(ComputerContext context)
{
this.context = context;
}
[HttpGet]
[EnableQuery]
public IQueryable<ComputerDto> GetComputers()
{
return this.context.Computers.Select(c => new ComputerDto
{
Id = c.Id,
Name = c.Name,
Disks = c.Disks.Select(d => new DiskDto
{
Letter = d.Letter,
Capacity = d.Capacity
}).ToList()
});
}
}
此查询有效,但由于我正在手动创建列表,因此磁盘已经扩展。
https://localhost:46324/api/computers?$filter=startswith(name,'t')
并输出
{
"@odata.context": "https://localhost:46324/api/$metadata#Collection(ODataPlayground.Dtos.ComputerDto)",
"value": [
{
"Id": 14,
"Name": "TestComputer1",
"Disks": [
{
"Letter": "C",
"Capacity": 234.40
},
{
"Letter": "D",
"Capacity": 1845.30
}
]
},
{
"Id": 15,
"Name": "TestComputer2",
"Disks": [
{
"Letter": "C",
"Capacity": 75.50
},
{
"Letter": "D",
"Capacity": 499.87
}
]
}
]
}
如果我随后尝试使用以下查询扩展“磁盘”,则会出现错误:
https://localhost:46324/api/computers?$filter=startswith(name,'t')&$expand=disks
错误
{
"error": {
"code": "",
"message": "The query specified in the URI is not valid. Property 'disks' on type 'ODataPlayground.Dtos.ComputerDto' is not a navigation property or complex property. Only navigation properties can be expanded.",
"details": [],
"innererror": {
"message": "Property 'disks' on type 'ODataPlayground.Dtos.ComputerDto' is not a navigation property or complex property. Only navigation properties can be expanded.",
"type": "Microsoft.OData.ODataException",
"stacktrace": "...really long stack trace removed for compactness..."
}
}
}
问题
非Dto输出
{
"@odata.context": "https://localhost:46324/api/$metadata#Collection(ODataPlayground.Dtos.ComputerDto)",
"value": [
{
"Id": 14,
"Name": "TestComputer1",
"Disks": [
{
"Id": 16,
"ComputerId": 14,
"Letter": "C",
"Capacity": 234.40
},
{
"Id": 17,
"ComputerId": 14,
"Letter": "D",
"Capacity": 1845.30
}
]
}
]
}
所需的输出(上面带有$ filter和$ expand查询)
{
"@odata.context": "https://localhost:46324/api/$metadata#Collection(ODataPlayground.Dtos.ComputerDto)",
"value": [
{
"Id": 14,
"Name": "TestComputer1",
"Disks": [
{
"Letter": "C",
"Capacity": 234.40
},
{
"Letter": "D",
"Capacity": 1845.30
}
]
}
]
}
更新#1
如果我将Automapper添加到组合中,并尝试使用带有以下代码的ProjectTo
方法:
//// Inject context and mapper
public ComputersController(ComputerContext context, IMapper mapper)
{
this.context = context;
this.mapper = mapper;
}
[HttpGet]
[EnableQuery]
public IQueryable<ComputerDto> GetComputers()
{
return this.context.Computers.ProjectTo<ComputerDto>(mapper.ConfigurationProvider);
}
我遇到了另一个错误:
InvalidOperationException: When called from 'VisitLambda', rewriting a node of type
'System.Linq.Expressions.ParameterExpression' must return a non - null value of the same type.
Alternatively, override 'VisitLambda' and change it to not visit children of this type.
答案 0 :(得分:5)
我似乎能够将顶级类作为dto返回,仅公开客户端可能需要的属性,但是还可以将dto作为导航属性公开并返回?
有可能,但是您需要解决一些建模和实现方面的问题。
首先,建模。 OData仅支持实体类型的集合导航属性。因此,为了将ComputerDto.Disks
属性映射为导航属性,您需要设置DiskDto
实体类型。进而需要它具有密钥。因此,可以在其中添加Id
属性,或将其他一些属性(例如,Letter
)与之关联:
//builder.ComplexType<DiskDto>();
builder.EntityType<DiskDto>().HasKey(e => e.Letter);
现在Disks
属性将不包含$expand
选项,并且还将消除原始的OData异常。
这全部与OData Edm模型有关,并为$expand
启用了Disks
选项。
下一个要解决的问题与OData和EF Core查询实现细节有关。运行过滤的查询(无$expand
)会产生所需的JSON输出(不包括Disks
),但是生成的EF Core SQL查询是
SELECT [c].[Id], [c].[Name], [d].[Letter], [d].[Capacity], [d].[Id]
FROM [Computers] AS [c]
LEFT JOIN [Disks] AS [d] ON [c].[Id] = [d].[ComputerId]
WHERE (@__TypedProperty_0 = N'') OR ([c].[Name] IS NOT NULL AND (LEFT([c].[Name], LEN(@__TypedProperty_0)) = @__TypedProperty_0))
ORDER BY [c].[Id], [d].[Id]
如您所见,它包括不必要的联接和列,效率不高。
使用$expand
选项,您将获得VisitLambda
异常,该异常来自EF Core 3.1查询转换管道,是由ToList()
成员投影中的Disks
调用引起的,这又是必需的,因为目标属性类型是ICollection<DiskDto>
,并且没有编译时错误。可以通过使属性类型为IEnumerable<DiskDto>
并从投影中删除ToList()
来解决,这可以消除异常,但再次会产生效率更低的SQL查询
SELECT [c].[Id], [c].[Name], [d].[Letter], [d].[Capacity], [d].[Id], @__TypedProperty_2, [d0].[Letter], [d0].[Capacity], CAST(1 AS bit), [d0].[Id]
FROM [Computers] AS [c]
LEFT JOIN [Disks] AS [d] ON [c].[Id] = [d].[ComputerId]
LEFT JOIN [Disks] AS [d0] ON [c].[Id] = [d0].[ComputerId]
WHERE (@__TypedProperty_0 = N'') OR ([c].[Name] IS NOT NULL AND (LEFT([c].[Name], LEN(@__TypedProperty_0)) = @__TypedProperty_0))
ORDER BY [c].[Id], [d].[Id], [d0].[Id]
这意味着,尝试直接在EF Core投影查询上直接使用OData查询是有问题的。
作为解决实施问题的一种方法,我建议使用AutoMapper.Extensions.OData扩展名:
从
ODataQueryOptions
创建LINQ表达式并执行查询。
您需要安装软件包AutoMapper.AspNetCore.OData.EFCore,使用与此类似的AutoMapper配置(本质是启用null收集和显式扩展)
cfg.AllowNullCollections = true;
cfg.CreateMap<Computer, ComputerDto>()
.ForAllMembers(opt => opt.ExplicitExpansion());
cfg.CreateMap<Disk, DiskDto>()
.ForAllMembers(opt => opt.ExplicitExpansion());
(注意:通过这种方法,属性类型可以保持ICollection<DiskDto>
)
并更改与此类似的控制器方法(本质是不使用EnableQuery
,添加options参数并返回IEnumerable
/ ICollection
而不是{ {1}})
IQueryable
现在,两个输出以及生成的SQL查询都将按预期进行:
输出:
using AutoMapper.AspNet.OData;
[HttpGet]
public async Task<IEnumerable<ComputerDto>> GetComputers(
ODataQueryOptions<ComputerDto> options) =>
await context.Computers.GetAsync(mapper, options, HandleNullPropagationOption.False);
SQL查询:
{
"@odata.context": "https://localhost:5001/api/$metadata#Collection(ODataTest.Dtos.ComputerDto)",
"value": [
{
"Id": 1,
"Name": "TestComputer1"
},
{
"Id": 2,
"Name": "TestComputer2"
}
]
}
SELECT [c].[Id], [c].[Name]
FROM [Computers] AS [c]
WHERE [c].[Name] IS NOT NULL AND ([c].[Name] LIKE N't%')
输出:
$expand=disks
SQL查询:
{
"@odata.context": "https://localhost:5001/api/$metadata#Collection(ODataTest.Dtos.ComputerDto)",
"value": [
{
"Id": 1,
"Name": "TestComputer1",
"Disks": [
{
"Letter": "C",
"Capacity": 234.4
},
{
"Letter": "D",
"Capacity": 1845.3
}
]
},
{
"Id": 2,
"Name": "TestComputer2",
"Disks": [
{
"Letter": "C",
"Capacity": 75.5
},
{
"Letter": "D",
"Capacity": 499.87
}
]
}
]
}