Efcore: Properties on owned types do not respect IsRequired()

Created on 10 Jul 2019  路  6Comments  路  Source: dotnet/efcore

Description

Properties on owned types are nullable in the database even when IsRequired() is set.

Steps to reproduce

With the follwing entities

```c#
public class Parent
{
public int Id { get; set; }
public OwnedType OwnedProperty { get; set; }

public int ParentRequiredInt { get; set; }
public string ParentRequiredString { get; set; }

}

public class OwnedType
{
public int OwnedRequiredInt { get; set; }
public string OwnedRequiredString { get; set; }
}


and the following configuration

```c#
modelBuilder.Entity<Parent>(entity =>
{
    entity.Property(x => x.ParentRequiredInt).IsRequired();
    entity.Property(x => x.ParentRequiredString).IsRequired();

    entity.OwnsOne(x => x.OwnedProperty, y =>
    {
        y.Property(a => a.OwnedRequiredInt).IsRequired();
        y.Property(a => a.OwnedRequiredString).IsRequired();
    });
});

Generating the migration results in:

image

The required properties on Parent have nullable: false as expected, but the required properties on OwnedType are nullable: true.

Further technical details

EF Core version: 3.0.0-preview5
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2019 16.2 Preview 3

closed-question customer-reported

All 6 comments

Owned properties are optional. i.e. For given parent, OwnedProperty may be null. That is represented in database using null values in those columns hence you see database column being created as nullable. EF will create on client side as required for them. (If you notice OwnedType.OwnedRequiredInt is int type so it is never going to take null as values anyway)

@smitpatel @AndriySvyryd Isn't this a duplicate of #15607

@ajcvickers - Reading the post, I don't feel they are duplicate. It is the same mismatch, when you put is IsRequired on a property on derived type but migration still generates a nullable column.

The issue is with inconsistency.
An int property on Parent does not allow null values and generates a non-nullable column by default.
An int property on OwnedType does not allow null values and generates a _nullable_ column by default, and still generates a nullable column when IsRequired is set.

If this is expected behaviour, then it should not be possible to set IsRequired on owned types as it causes confusion.

@AndrewGriffithsFG This is expected. As you said setting IsRequired means the null values aren't allowed for that property. But the owned type itself is still optional. With #15607 it would be possible to make the owned navigation required as well resulting in non-nullable columns for required properties.

Commented on #15607, and now agree this should be closed.

Was this page helpful?
0 / 5 - 0 ratings