gpt4 book ai didi

c# - 在 .net 核心中使用带有 graphql 的泛型类

转载 作者:行者123 更新时间:2023-11-30 15:53:07 31 4
gpt4 key购买 nike

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

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

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

public TFrom From { get; set; }

public TTo To { get; set; }

#endregion
}

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

RangeModel<double?, double?>

RangeModel<int?, int?>

...等等。

我试过制作 RangeModelType继承ObjectGraphType的类:

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

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

Unable to cast object of type GraphQL.Types.ObjectGraphType1[GraphQlStudy.Models.GraphQL.Types.RangeModelType2[System.Nullable1[System.Double],System.Nullable1[System.Double]]]' to type 'GraphQL.Types.ScalarGraphType'.

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

谁能帮帮我?

谢谢,

最佳答案

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

  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."});

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

希望这对您有所帮助。

关于c# - 在 .net 核心中使用带有 graphql 的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53039419/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com