Stupid Question time: How to store null in an Entity Framework collection?

I have, in part, the following objects:

public class GameDBObject
{
    public string? Id { get; set; } = null;
// other fields...
    public IList<GameHistoryEntryView>? History { get; set; } = null;
}
public class GameHistoryEntry
{
// other fields...
    public ICollection<GuessResult?>? Results { get; set; }
}
public class GuessResult
{
    // a number of scalar fields
}

This works until I try to store a null entry in the GameHistoryEntry.Results list. As soon as I try to save the database context with a null entry in that list, I get a System.ArgumentNullException: 'Value cannot be null. (Parameter 'key')' error.

The collection already says the type is the nullable GuessResult type, so null should be allowed. How can I make this work?

The ? symbol for reference types is a compiler annotation for checking and not part of the core type system in .NET.

i.e. Reflection will tell you this property is a ICollection<GuessResult> and the ? won’t affect that, unlike say an int? which will come through as a Nullable<int> rather than an int. The compiler does put a [Nullable(2)] attribute on the property but EF doesn’t read that at this time. I think Non-nullable navigation creates nullable foreign key when principal key is alternate · Issue #30344 · dotnet/efcore · GitHub is the tracking issue.

I think you should be able to configure it as not required using the model builder, e.g.

mb.Entity<GameHistoryEntry>().Property(e => e.Results).IsRequired(false)

So what I actually want to do is make it so individual items in the GameHistoryEntry.Results array can be null. Would setting e.Results itself to not be required do that, or would that just make it so the Results field itself could be null?

Okay, I’m just going to rework the logic to not require nullable GuessResult objects. It’s probably clearer this way anyway.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.