简体   繁体   English

ResolveWith 中的 DbContext,HotChocolate GraphQL

[英]DbContext in ResolveWith, HotChocolate GraphQL

So I just get started, I have an entity which keeps the data from other entities not by a direct relation but with keeping the EntityId and EntityType(Enum).所以我才刚刚开始,我有一个实体,它不是通过直接关系而是通过保持 EntityId 和 EntityType(Enum) 来保存来自其他实体的数据。 When I read these records from GraphQL I expect to resolve a field with a resolver as follow,当我从 GraphQL 读取这些记录时,我希望用解析器解析一个字段,如下所示,

        public class AssignmentResolver
        {
            public object GetEntity( Assignment assignment, AppDbContext context)
            {
                        if(assignment.EntityType == AssignmentEntityType.PERSON) 
                       {
                                return context.People.FirstOrDefault(x => x.Id == assignment.EntityId);
                       }
                       // And more checks
                      return null;
            }
        }

Then I can say那我可以说

    public class AssignmentQueryType: ObjectType<Assignment>
    {
        protected override void Configure(IObjectTypeDescriptor<Assignment> descriptor)
        {
            descriptor.Field("entity").ResolveWith<AssignmentResolver>(x => x.GetEntity(default!, default!));
        }
    }

I wanna know if this is right or is there a better way... I mean the better way would be using a document database for this but that's not an option for now.我想知道这是正确的还是有更好的方法...我的意思是更好的方法是为此使用文档数据库,但现在还不是一个选择。 I also maybe instead of putting the EntityType and EntityId can simply set an actual relation to those other entities but I wanna see if this current way is possible.我也可能不是放置 EntityType 和 EntityId 而是可以简单地设置与其他实体的实际关系,但我想看看这种当前方式是否可行。

Well that was fast.好吧,那很快。

I found my problem.我发现了我的问题。 It seems that in the resolver I cannot just return an object because the schema should be clear when being read.似乎在解析器中我不能只返回 object,因为模式在读取时应该是清晰的。

So from the resolver if I return a viewModel which is shared between all those entities then we are good to go.因此,如果我从解析器返回一个在所有这些实体之间共享的 viewModel,那么我们对 go 很好。

So the GetEntity code will change to所以 GetEntity 代码将更改为

            public EntityViewModel GetEntity( Assignment assignment, [Service] AppDbContext context)
            {
                        if(assignment.EntityType == AssignmentEntityType.PERSON) 
                       {
                                var entity = context.People.FirstOrDefault(x => x.Id == assignment.EntityId);
                                return new EntityViewModel(entity);
                       }
                       // And more checks
                      return null;
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM