Skip to content

Instantly share code, notes, and snippets.

@joelmandell
Created November 21, 2019 22:46
Show Gist options
  • Save joelmandell/23b99ff42be495836d9749af3641d69b to your computer and use it in GitHub Desktop.
Save joelmandell/23b99ff42be495836d9749af3641d69b to your computer and use it in GitHub Desktop.
Helper to create Lamda expression to use in Linq-query when combining graphql-dotnet with entity framework and iqueryables.
using System;
using System.Linq;
using System.Linq.Expressions;
using GraphQL.Language.AST;
using GraphQL.Types;
public static class GQLHelper
{
public static Expression<Func<T, T>> GraphQLFields<T>(ResolveFieldContext<object> ctx)
{
string fields = String.Join(",",ctx.FieldAst
.SelectionSet
.Selections
.Select(x => (x as Field).Name)
.ToArray());
//Create new class of type T.
var xNew = Expression.New(typeof(T));
//Create parameter name for the LINQ/Lambda-expression.
//Example: .Select(o => ...);
var xParameter = Expression.Parameter(typeof(T), "o");
//Iterate GraphQL query-fields and build properties to add to the body.
var bindings = fields.Split(',').Select(o => o.Trim()).Select(o =>
{
var mi = typeof(T).GetProperties()
.Where(prop => prop.Name.ToLower() == o.ToLower())
.FirstOrDefault();
if ((mi == null))
return null;
var xOriginal = Expression.Property(xParameter, mi);
return Expression.Bind(mi, xOriginal);
}).Where(s => s != null);
var xInit = Expression.MemberInit(xNew, bindings);
var lambda = Expression.Lambda<Func<T, T>>(xInit, xParameter);
return lambda;
}
}
@joelmandell
Copy link
Author

I might improve this and publish as a nuget-package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment