Skip to content

[Bug] Enabling Nullable Reference Types does not make navigation properties nullable #151

@Leosori

Description

@Leosori

Describe the bug
If EnableNullableReferenceTypes is set to true, non-collection nav properties that belong to a nullable property are not marked as nullable. This causes Entity Framework to use INNER JOINs instead of OUTER JOINs when generating the SQL query.

Example of the currently generated entity:

class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int FirstAddressId {get; set;}
    public int? SecondAddressId {get; set;}

    // nav property
    public virtual Address FirstAddress { get; set; } = default!;
    public virtual Address SecondAddress { get; set; } = default!;
}

Expected behavior

class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int FirstAddressId {get; set;}
    public int? SecondAddressId {get; set;}

    // nav property
    public virtual Address FirstAddress { get; set; } = default!;
    public virtual Address? SecondAddress { get; set; }
}

Additional context
Property template looks currently like this and uses property-isnullable

public {{property-type}} {{property-name}} { get; set; }{{#if nullable-reference-types }}{{#unless property-isnullable}} = default!;{{/unless}}{{/if}}

Nav properties have this template:

{{#if nav-property-collection}}
        public virtual ICollection<{{nav-property-type}}> {{nav-property-name}} { get; set; }{{#if nullable-reference-types}} = default!;{{/if}}
{{else}}
        public virtual {{nav-property-type}} {{nav-property-name}} { get; set; }{{#if nullable-reference-types}} = default!;{{/if}}
{{/if}}

In order to get it right, the nav property template needs access to property-isnullable

{{#if nav-property-collection}}
        public virtual ICollection<{{nav-property-type}}> {{nav-property-name}} { get; set; }{{#if nullable-reference-types}} = default!;{{/if}}
{{else}}
        public virtual {{nav-property-type}}{{#if nullable-reference-types}}{{#if property-isnullable}}?{{/if}}{{/if}} {{nav-property-name}} { get; set; }{{#if nullable-reference-types}}{{#unless property-isnullable}} = default!;{{/unless}}{{/if}}
{{/if}}

AFAIK should the collection variant stay non-nullable because this is covered by an empty collection.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions