Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/EFCore.Relational/Metadata/Internal/RelationalModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -634,8 +634,16 @@ private static void CreateContainerColumn<TColumnMappingBase>(
{
complexType = (IComplexType)mappedType;
#pragma warning disable EF1001 // Internal EF Core API usage.
var chain = complexType.ComplexProperty.GetChainToComplexProperty(fromEntity: true);
jsonColumn.IsNullable = complexType.ComplexProperty.IsNullable
|| complexType.ComplexProperty.GetChainToComplexProperty(fromEntity: true).Any(p => p.IsNullable);
|| chain.Any(p => p.IsNullable);

if (chain[0].DeclaringType is IEntityType declaringEntityType
&& declaringEntityType.BaseType != null)
{
// if the complex property is defined on a derived type, the column must be made nullable
jsonColumn.IsNullable = true;
}
Comment thread
AndriySvyryd marked this conversation as resolved.
Outdated
#pragma warning restore EF1001 // Internal EF Core API usage.
}
}
Expand Down
32 changes: 32 additions & 0 deletions test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3201,6 +3201,26 @@ public void Container_column_type_is_used_for_complex_collection_json_column()
Assert.IsType<JsonColumn>(jsonColumn);
}

[ConditionalFact]
public void Complex_property_json_column_is_nullable_in_TPH_hierarchy()
{
var modelBuilder = CreateConventionModelBuilder();

modelBuilder.Entity<TphBaseEntity>();
modelBuilder.Entity<EntityWithoutComplexProperty>();
modelBuilder.Entity<TphEntityWithComplexProperty>()
.ComplexProperty(e => e.ComplexProperty, b => b.ToJson());

var model = modelBuilder.FinalizeModel();
var relationalModel = model.GetRelationalModel();

var table = relationalModel.Tables.Single();
var jsonColumn = table.Columns.Single(c => c.Name == "ComplexProperty");

Assert.True(jsonColumn.IsNullable);
Assert.IsType<JsonColumn>(jsonColumn);
}

private static IRelationalModel Finalize(TestHelpers.TestModelBuilder modelBuilder)
=> modelBuilder.FinalizeModel(designTime: true).GetRelationalModel();

Expand Down Expand Up @@ -3318,6 +3338,18 @@ private class EntityWithComplexCollection
public List<ComplexData> ComplexCollection { get; set; }
}

private abstract class TphBaseEntity
{
public int Id { get; set; }
}

private class EntityWithoutComplexProperty : TphBaseEntity;

private class TphEntityWithComplexProperty : TphBaseEntity
{
public ComplexData ComplexProperty { get; set; }
}

private class ComplexData
{
public string Value { get; set; }
Expand Down
Loading