Efcore: Owned property returned as null when all of its properties are null

Created on 7 May 2020  路  4Comments  路  Source: dotnet/efcore


Inside my entity Submission:

public class Submission
{
   public string Id { get; private set; }
   ...
   public ObjectData ObjectData {get; private set;}
   ...
}

I have an owned entity of type ObjectData:

public class ObjectData
{
    // Properties
    public byte? CategoryType { get; private set; }
    public decimal? Cost { get; private set; }

    // Constructors
    public ObjectData(
        byte? objectCategoryType,
        decimal? objectCost
    )
    {
        CategoryType = objectCategoryType;
        Cost = objectCost;
    }

    private ObjectData() { }
}

Their relationship is configured inside the Context.OnModelCreating like so:

modelBuilder.Entity<Submission>().OwnsOne<ObjectData>(e => e.ObjectData);

When a Submission = { ObjectData = { ObjectCategoryType = null, ObjectCost = null } } is persisted, and then later fetched from the database, it will return as a Submission = { ObjectData = null }.

I expected it to return as Submission = { ObjectData = { ObjectCategoryType = null, ObjectCost = null } }.

It seems that EFCore determines if the owned entity is null by checking if all of its columns have null values, instead of differentiating between an "empty" owned property and a null owned property.

I need the ObjectData to always exist and all of its properties to be nullable. Any ideas on how to remedy this?

Further technical details

EF Core version: 3.1.3
Database provider: Microsoft.EntityFrameworkCore.SqlServer v3.1.3
Target framework: .NET Framework 4.8 / .NET Framework 3.1

closed-by-design customer-reported

Most helpful comment

All 4 comments

@smitpatel Your answer does not help me solve my issue.
What would be the designed EFCore solution for my usecase?

If you need to always create the owned referenced regardless of property values, hence making the dependent required see #12100

For anyone coming here with a similiar problem, I made a simple workaround, until #12100 feature is released.
I added a dummy bool property to the owned entity class, which I always set to a non-null value. That way, my owned entity never has all null values, and is thus never returned as null from the DB.

Was this page helpful?
0 / 5 - 0 ratings