将 GraphQL 查询映射到 Select() linq 到 sql

Tấn*_*ang 8 c# linq-to-sql .net-core graphql azure-cosmosdb

我正在使用 .NET CoreGraphQL和.NET Core 构建一个 Web API DocumentDb

理论上,GraphQL优化数据通过网络传输,从而避免过度获取数据。但是我认识到后端服务器和数据库在查询数据库时正在做额外的不必要的工作(查询整个文档)。

这里最好的策略是使用Select()我们需要获取的特定属性。但我不知道如何从如此复杂的客户查询中构建表达式。

任何帮助真的很感激。

谢谢

Dav*_*man 1

要将 linq 表达式转换为 graphql 查询,您可以使用库: https: //github.com/RDavydenko/SmartGraphQLClient

  1. 安装 Nuget 包:
Install-Package SmartGraphQLClient
Run Code Online (Sandbox Code Playgroud)
  1. 将服务添加到 DI:
services.AddSmartGraphQLClient();
Run Code Online (Sandbox Code Playgroud)
  1. 使用 linq 语法:
using SmartGraphQLClient;

GraphQLHttpClient client = ... // from DI

var users = await client.Query<UserModel>("users")
    .Include(x => x.Roles)
    .ThenInclude(x => x.Users)
    .Where(x => x.UserName.StartsWith("A") || x.Roles.Any(r => r.Code == RoleCode.ADMINISTRATOR))
    .Select(x => new 
    {
        x.Id,
        Name = x.UserName,
        x.Roles,
        IsAdministrator = x.Roles.Any(r => r.Code == RoleCode.ADMINISTRATOR)
    })
    .Skip(5)
    .Take(10)
    .Argument("secretKey", "1234")
    .ToListAsync();
Run Code Online (Sandbox Code Playgroud)

您的请求将被转换为 graphql-query:

{ 
    users (
      where: {
        or: [ 
          { userName: { startsWith: "A" } }
          { roles: { some: { code: { eq: ADMINISTRATOR } } } }
        ]
      }
      skip: 5
      take: 10
      secretKey: "1234"
  ) {
        id
        userName
        roles {
            code
            name
            description
            id
            users {
                userName
                age
                id
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)