使用 Automapper 10.1.1 和 HotChocolate 11.1 来映射可查询对象

问题描述

我正在尝试使用 Automapper 投影我的 EF Core 查询以允许我的应用程序中的第 3 层,但是我在允许 HotChocolate 请求我的 DTO 上的字段并告诉 Automapper 在投影过程中包含这些字段时遇到了一些麻烦。

一些重要的事前:

  • 当两个属性都存在时,Automapper 将请求地图上的所有 NavigationProperties
  • 除非存在 ExplicitExpansion 设置
  • 如果在地图上设置了 ExplicitExpansion,则 HotChocolate 无法使用 IQueryable 扩展 [UseProjection] 的导航属性

所以我可以一次性加载所有导航属性,也可以不加载。

如何告诉 ether HotChocolate 映射 IQueryable 中的实体,或者如何在查询函数中获取所需的键以告诉 AutoMapper 使用 IQueryable<T>.ProjectTo() 方法扩展哪些属性?

解决方法

你尝试了吗?

queue = []

def next(client,queue,song):
    if len(queue)>0:
        new_song= queue[0]
        del queue[0]
        play(client,new_song)

@bot.command()
async def join (ctx):
    member = ctx.author
    if not ctx.message.author.voice:
        await ctx.send(f"{member.mention} You are not connected to a voice channel  ❌")
    else:
        channel=ctx.message.author.voice.channel
        await channel.connect()


@bot.command(help="This command plays a song.")
async def play (ctx,*args):
    server = ctx.message.guild
    voice_channel= server.voice_client
    url=""
    for word in args:
        url+=word
        url+=''

    async with ctx.typing():
        player = await YTDLSource.from_url(url,loop=bot.loop,stream=True)
        queue.append(player)
        voice_channel.play (player,after=lambda e: next(ctx))
        
    await ctx.send(f"**Now playing:** {player.title}")

如果投影不太复杂,这应该可行

如果投影顺序有问题,您也可以创建自定义属性

public class Query
{
    [UseProjection] //<----
    public IQueryable<FooDto> GetFoos([Service]YourService svc)=> svc.GetFooDtos();
}
    public class YourCustomMiddlewareAttribute : ObjectFieldDescriptorAttribute
    {
        public override void OnConfigure(
            IDescriptorContext context,IObjectFieldDescriptor descriptor,MemberInfo member)
        { 
            descriptor.Type<ListType<ObjectType<PersonDto>>>();
            descriptor.Use(next => async context =>
            {
                await next(context);
                if (context.Result is IQueryable<Person> persons)
                { 
                    context.Result = persons
                         .ProjectTo<PersonDto>()
                         .ToListAsync(context.RequestAborted);
                }
            })
        }
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...