Assuming you’ve build a resolver primarily for returning Entity Framework results using the build int GraphQL Hot Chocolate extensions. You are following the DI pattern recommended by the Hot Chocolate team here:
Your code likely looks as follows:
This works great when you are just using Entity Framework and returning an IQueryable which is what typically you get when you work with EF.
Say however, you want to either get some data from someplace else, or you want to calculate something from EF and just return a concret type. Assuming you still want to use EF, you need to somehow get the EF context and then return a type that is not an EF type.
I happen to be the organizer of Silicon Valley Code Camp and I often have crazy ideas for things I want to show and often, I need to write custom back end processing to get what I need. In this case, not so crazy, but say I want to do the following:
Generate a return that shows how many presenters at each years code camp over the years
Let’s do it.
For those in a hurry, here is the solution. I’ll explain it after this if it’s not obvious to you what I’ve done.
Here’s the explanation:
[ScopedService] ApplicationDbContext context is no longer going to give us a
valid EF context so we need to use the factory pattern to generate our own and then store
an instance of the factory
_contextFactory. Then, in the method
GetSpeakersPerCodeCampYear, first thing
is we use that factory to get an EF context we can use in the method for all our work. That’s the line:
using var context = _contextFactory.CreateDbContext();
Next, we do a bunch of Entity Framework work to get the result we want. For me, this kind of coding is super fast as I know my data models well and I’m using them all the time with LINQ. I won’t explain the details, as it’s not really relevant, just think of it as “a bunch of stuff”.
As an aside, if you’re thinking, “wow, that’s going to be really slow, I’d never put something like this in production code!”. Well, I’d have to disagree with you. I’m running against a 1GB database (our production data for our real code camp), and even though this ran 14 individual queries, each with multiple join and where clauses, each query took under 1 millisecond so not much of a load.
Finally, I’m returning speakerCounts which is just a
List<SpeakerCountByYear>. Notice that I created my own
SpeakerCountByYear to make that happen.
Be flexible when creating resolvers and you can do practially anything you want, including using all your Entity Framework (EF) results.