C#C
C#6mo ago
Nasdack

EF Core Nullable Foreign Key Relationship

        x.HasOne(t => t.Client)
            .WithMany()
            .HasForeignKey(f => f.ClientId)
            .OnDelete(DeleteBehavior.Restrict)
            .IsRequired(false);

I have this one to many FK relationship configuration in EF Core that I want to be nullable. If I set the type of ClientId to be nullable (which is a custom class that wraps up a Guid value which the entire codebase uses), EF Core will complain about:
System.InvalidOperationException: The client projection contains a reference to a constant expression of 'Common.Identifier'. This could potentially cause a memory leak; consider assigning this constant to a local variable and using the variable in the query instead.

with the generated pre-compilation query being:
        ClientId = namelessParameter{0}.ClientId == null ? 00000000-0000-0000-0000-000000000000 : new Identifier{ Value = (Guid)namelessParameter{0}.ClientId.Value }

EF Core is doing a ternary conditional operation and is initializing Identifier to its default constant value when not set, which is causing this issue. I don't know how to instruct it not to do that.

Right now I cannot mess with the custom Identifier? class so using Guid? instead is not an ideal option. Using IsRequired(false) instead of Nullable<> also brought no results. I have also tried this converter:
public sealed class IdentifierConverter() : ValueConverter<Identifier, Guid>(id =>      id.Value,
    value => value);

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        configurationBuilder
            .Properties<Identifier>()
            .HaveConversion<IdentifierConverter>();
    }

to no avail, even with a nullable version.
Was this page helpful?