I’m spending a lot (read: “waaay to many”) time learning GraphQL. One of the things I had to figure out was how to use Guids inside my GraphQL schema.
On one of my projects we are using Guids. Here is the mapping I tried to use:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Product | |
{ | |
public Guid Id {get;set;} | |
public string Description {get;set;} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProductType:ObjectGraphType<Product> | |
{ | |
public ProductType() | |
{ | |
Field(m => m.Id); | |
Field(m => m.Description); | |
} | |
} |
When loading my GraphQL endpoint this resulted in the following error message:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Product | |
{ | |
public Guid Id {get;set;} | |
public string Description {get;set;} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProductType:ObjectGraphType<Product> | |
{ | |
public ProductType() | |
{ | |
Field(m => m.Id); | |
Field(m => m.Description); | |
} | |
} |
The type: Guid cannot be coerced effectively to a GraphQL type
To fix it I had to explicitly specify the FieldType as IdType:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProductType:ObjectGraphType<Product> | |
{ | |
public ProductType() | |
{ | |
Field(m => m.Id, type: typeof(IdGraphType)); | |
Field(m => m.Description); | |
} | |
} |