0

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

提前几个重要的点:

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

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

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

4

1 回答 1

0

你试过了吗?

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);
                }
            })
        }
    }
public class Query
{
    [YourCustomMiddleware]
    [UseProjection]
    public IQueryable<FooDto> GetFoos([Service]YourService svc)=> svc.GetFooDtos();
}
于 2021-04-27T13:54:50.610 回答