在工作中,我们在数据层和graphql-dotnet上使用EFCore来管理API请求,我在使用GraphQL突变更新一些大对象时遇到问题.当用户在模型上发送部分更新时,我们希望仅在数据库中更新实际由突变更改的字段.我们遇到的问题是,当我们直接将输入映射到实体时,有些字段被有目的地传递为null,或者根本没有在字段上指定字段,我们将属性值作为null.这样我们就无法将更改发送到数据库,否则我们会错误地将一堆字段更新为null.
因此,我们需要一种方法来识别哪些字段是在变异中发送的,只是更新它们.在JS中,这是通过检查属性值是否未定义来实现的,如果值为null,我们知道它是故意传递为null.
我们一直在考虑的一些解决方法是使用Dictionary上的反射来仅更新指定的字段.但我们需要将反射传播到每一个突变.另一个解决方案是对我们模型上的每个可空属性都有一个isChanged属性,并在引用的属性setter上更改ir,但是...... cmon ...
我提供了一些代码作为这种情况的例子如下:
人类:
public class Human
{
public Id { get; set; }
public string Name { get; set; }
public string HomePlanet { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
GraphQL类型:
public class HumanType : ObjectGraphType<Human>
{
public HumanType()
{
Name = "Human";
Field(h => h.Id).Description("The id of the human.");
Field(h => h.Name, nullable: true).Description("The name of the human.");
Field(h => h.HomePlanet, nullable: true).Description("The home planet of the human.");
}
}
Run Code Online (Sandbox Code Playgroud)
输入类型:
public class HumanInputType : InputObjectGraphType
{ …Run Code Online (Sandbox Code Playgroud)