使用带有OData查询的实体框架的导航DTO属性

时间:2020-10-27 04:44:13

标签: c# asp.net-core entity-framework-core odata

开发环境

  • ASP.NET Core 3.1
  • Microsoft.EntityFrameworkCore 3.1.9
  • Microsoft.AspNetCore.OData 7.5.1

模型

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返回,仅公开客户端可能需要的属性,但是还可以将dto作为导航属性公开并返回?

非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.

1 个答案:

答案 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
                }
            ]
        }
    ]
}