Back to Graphql Dotnet

GQL015: Can't infer a Field name from expression

docs2/site/docs/analyzers/gql015.md

8.8.42.1 KB
Original Source

GQL015: Can't infer a Field name from expression

Value
Rule IDGQL015
CategoryUsage
Default severityError
Enabled by defaultYes
Code fix providedNo
Introduced inv7.9

Cause

This rule triggers when field defined with expression which is not a simple member access expression.

Rule description

When defining fields with expression, the GraphQL.NET tries to infer the field name from the expression. This is only possible when the expression is a simple member access expression like field or property. For example

c#
p => p.FirstName

How to fix violations

Use an overload that accepts a name parameter to define the field name explicitly.

Example of a violation

c#
public class PersonGraphType : ObjectGraphType<Person>
{
    public PersonGraphType()
    {
        Field(p => $"{p.FirstName} {p.LastName}");
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Example of how to fix

Define the field name explicitly

c#
public class PersonGraphType : ObjectGraphType<Person>
{
    public PersonGraphType()
    {
        Field("FullName", p => $"{p.FirstName} {p.LastName}");
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable GQL015
// The code that's violating the rule is on this line.
#pragma warning restore GQL015

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.cs]
dotnet_diagnostic.GQL015.severity = none

For more information, see How to suppress code analysis warnings.