Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping GraphQL query to Select() linq to sql

I am building an Web API with .NET core using GraphQL and DocumentDb.

In theory, GraphQL is optimized the data is shipped across the network and thus avoid over-fetching data. But I recognize that the backend server and database is doing the extra unnecessary work (query the entire document) when querying the database.

The best strategy here is using Select() to specific properties we need to fetch. But I have no idea how to build the expression from client's query that so complex.

Any help really appreciated.

Thanks

like image 367
Tan Sang Avatar asked Jun 17 '20 07:06

Tan Sang


People also ask

Can you use GraphQL with SQL?

Summary: Add a GraphQL API Layer to Any Database Databases store the world's data and provide interfaces like SQL and its variants that let users access and manipulate the data.

How does select work in LINQ?

Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.

Should I use LINQ to SQL?

More importantly: when it comes to querying databases, LINQ is in most cases a significantly more productive querying language than SQL. Compared to SQL, LINQ is simpler, tidier, and higher-level. It's rather like comparing C# to C++.


2 Answers

For a SQL expression if we want to query for jedis and we want the columns name and side, we can use the script as below:

SELECT name, side
FROM jedis;

Let's update the code with our query like so:

var json = schema.Execute(_ =>
{
    _.Query = "{ jedis { name, side } }";
});

Console.WriteLine(json);

and the result is: enter image description here

For more details, you could refer to this article and this one.

like image 102
Joey Cai Avatar answered Oct 15 '22 17:10

Joey Cai


But I have no idea how to build the expression from client's query that so complex.

What kind of complex query do you have? Just need to fetch only fields those are existed in grapql query? Well, at least one component that already tested in production I know. If you need solution from the box (looks like you have already had GraphQL.Net, so, it's under .net stack lib), might be sth like NReco.GraphQL could help you to resolve an issue (just need to set up graphql schema definitions in json-file and connection string to db) which is translating graphql query (even related, even with aggregate functions) to sql query with exactly the same fields as you have in graphql query.

like image 20
Dmitriy Avatar answered Oct 15 '22 16:10

Dmitriy