Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c# - 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.

question from:https://stackoverflow.com/questions/65951533/dbcontext-in-resolvewith-hotchocolate-graphql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...