【问题标题】:Use generic class with graphql in .net core在 .net 核心中使用带有 graphql 的泛型类
【发布时间】:2019-04-02 00:37:25
【问题描述】:

我是GraphQL 的新手,我正在制作一个用于管理学生和班级的小型​​网站。

在我的应用程序中,我有一个通用类:

public class RangeModel<TFrom, TTo>
    {
        #region Propertes

        public TFrom From { get; set; }

        public TTo To { get; set; }

        #endregion
    }

该类用于定义具有通用数据类型的范围。 范围可以是:

RangeModel&lt;double?, double?&gt;

RangeModel&lt;int?, int?&gt;

...等等。

我尝试创建一个继承 ObjectGraphTypeRangeModelType 类:

    public class RangeModelType<TFrom, TTo>: InputObjectGraphType<RangeModel<TFrom, TTo>>
        {
            public RangeModelType()
            {
                Field(x => x.From).Description("Minimum range");
                Field(x => x.To).Description("Maximum range");
            }
        }

并定义我的查询如下:

var studentsQueryArguments = new QueryArguments();
            studentsQueryArguments.Add(new QueryArgument<ListGraphType<IntGraphType>> { Name = "ids", Description = "Student indexes." });
            studentsQueryArguments.Add(new QueryArgument<ObjectGraphType<RangeModelType<double?, double?>>>{Name = "age", Description = "Age range of student."});
            Field<ListGraphType<StudentType>>(
                "students",
                arguments: studentsQueryArguments,
                resolve: context =>
                {
                    // Resolve data...
                    return results;
                });
        }

当我运行我的应用并进行查询时。一个异常被抛出,它说:

无法将 GraphQL.Types.ObjectGraphType1[GraphQlStudy.Models.GraphQL.Types.RangeModelType2[System.Nullable1[System.Double],System.Nullable1[System.Double]]]' 类型的对象转换为类型 'GraphQL. Types.ScalarGraphType'。

我一直在寻找使用 GraphQL 和泛型类的教程,但没有提及使用这种泛型类。

谁能帮帮我?

谢谢,

【问题讨论】:

  • 我对graphQL不太了解,但这看起来ObjectGraphType和ScalarGraphType不兼容,独立于泛型......您可以通过使用更简单的objectgraphtype来验证这一点。

标签: c# .net-core graphql asp.net-core-2.0 asp.net-core-webapi


【解决方案1】:

花了几个小时后,我有以下解决方案。

  1. RangeModel.cs 定义为:

    public class RangeModel<TFrom, TTo>
    {
        public TFrom From { get; set; }
    
        public TTo To { get; set; }
    }
    
  2. 定义RangeModelType.cs

    public class RangeModelType<TFrom, TTo> : InputObjectGraphType<RangeModel<TFrom, TTo>>
    {
        public RangeModelType()
        {
            var fromType = typeof(TFrom);
            Field(x => x.From, fromType.IsGenericType && fromType.GetGenericTypeDefinition() == typeof(Nullable<>));
    
            var toType = typeof(TTo);
            Field(x => x.To, toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
    }
    
  3. 这是我的查询参数:

    studentsQueryArguments.Add(new QueryArgument<RangeModelType<double?, double?>> {Name = "age", Description = "Age range of student."});
    

我不知道这个实现好不好。目前,它解决了我的问题。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多