简体   繁体   中英

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). When I read these records from GraphQL I expect to resolve a field with a resolver as follow,

        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.

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.

So from the resolver if I return a viewModel which is shared between all those entities then we are good to go.

So the GetEntity code will change to

            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;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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