我正在学习如何在graphql-dotnet中使用CustomScalar。
我的表中有一个tinyint列,从我读过的,我应该在C#中使用此列的字节。经过研究,我发现我需要创建一个ByteGraphType,但是我很难做到这一点。
我从这个链接https://github.com/graphql-dotnet/graphql-dotnet/issues/458得到了ByteGraphType示例,所以我认为它会起作用。
使用此代码,我可以查询表,但是,我的突变不起作用。我没有找到一个示例来演示如何使用字节列突变。我按照我的代码示例中所述进行了尝试,但在此行中(var avaliacao = context.GetArgument(“avaliacao”);),我的参数avaliacao.Nota返回null,我不确定如何继续。
有人能帮我吗?
谢谢
这是我的代码
//模型
[Column("nota")]
public byte Nota { get; set; }
//类型
Field<ByteGraphType>("Nota", resolve: context => context.Source.Nota);
//输入类型
Field<ByteGraphType>("nota");
//查询
Field<ListGraphType<AvaliacaoType>>(
"avaliacoes",
resolve: context => contextServiceLocator.AvaliacaoRepository.All());
//突变
Field<AvaliacaoType>(
"createAvaliacao",
arguments: new QueryArguments(
new QueryArgument<NonNullGraphType<AvaliacaoInputType>> { Name = "avaliacao" }
),
resolve: context =>
{
var schema = new Schema();
schema.RegisterValueConverter(new ByteValueConverter());
var avaliacao = context.GetArgument<Avaliacao>("avaliacao");
avaliacao.Nota.AstFromValue(schema, new ByteGraphType());
return contextServiceLocator.AvaliacaoRepository.Add(avaliacao);
});
// ByteGraphType
using GraphQL.Language.AST;
using GraphQL.Types;
using System;
namespace Api.Helpers
{
public class ByteGraphType : ScalarGraphType
{
public ByteGraphType()
{
Name = "Byte";
}
public override object ParseLiteral(IValue value)
{
var byteVal = value as ByteValue;
return byteVal?.Value;
}
public override object ParseValue(object value)
{
if (value == null)
return null;
try
{
var result = Convert.ToByte(value);
return result;
}
catch (FormatException)
{
return null;
}
}
public override object Serialize(object value)
{
return ParseValue(value).ToString();
}
public class ByteValueConverter : IAstFromValueConverter
{
public bool Matches(object value, IGraphType type)
{
return value is byte;
}
public IValue Convert(object value, IGraphType type)
{
return new ByteValue((byte)value);
}
}
public class ByteValue : ValueNode<byte>
{
public ByteValue(byte value)
{
Value = value;
}
protected override bool Equals(ValueNode<byte> node)
{
return Value == node.Value;
}
}
}
}
我需要的是能够保存具有tinyint列的表的记录。如果我将代码中的类型更改为int,我可以改变,但不能查询。
我改变了我的CustomScalar并且它有效:
using GraphQL.Language.AST;
using GraphQL.Types;
using System;
namespace Api.Helpers
{
public class ByteGraphType : ScalarGraphType
{
public ByteGraphType()
{
Name = "Byte";
Description = "ByteGraphType";
}
/// <inheritdoc />
public override object Serialize(object value)
{
return ParseValue(value).ToString();
}
/// <inheritdoc />
public override object ParseValue(object value)
{
byte result;
if (byte.TryParse(value?.ToString() ?? string.Empty, out result))
{
return result;
}
return null;
}
/// <inheritdoc />
public override object ParseLiteral(IValue value)
{
if (value is StringValue)
{
return ParseValue(((StringValue)value).Value);
}
return null;
}
}
}