Columns for nested owned types don't allow NULL although owned by derived entity.
EF Core uses TPH for inheritance. Therefore database columns for properties of derived entity types allow NULL even if the property type is not nullable. The same holds for owned types that are referenced from a derived entity type. But it doesn't hold for nested owned types. When saving a non-derived entity, this leads to a SqlException "Cannot insert the value NULL into column '...', table '...'; column does not allow nulls." Following exceptions details are from the code given below:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Data_SubData_Prop', table 'NestedOwnedWithinDerivedDb.dbo.Entity'; column does not allow nulls. INSERT fails.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple`2 parameters)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at NestedOwnedWithinDerived.Program.Main(String[] args) in Program.cs:line 58
Steps to reproduce
Running the following code leads to the above exception:
using System;
using Microsoft.EntityFrameworkCore;
namespace NestedOwnedWithinDerived
{
public class Entity
{
public Int64 Id { get; set; }
public Int32 Int { get; set; }
}
public class EntityWithOwned : Entity
{
public Int32 Prop { get; set; }
public OwnedData Data { get; set; }
public EntityWithOwned() => Data = new OwnedData();
}
public class OwnedData
{
public Int32 Prop { get; set; }
public OwnedSubData SubData { get; set; }
public OwnedData() => SubData = new OwnedSubData();
}
public class OwnedSubData
{
public Int32 Prop { get; set; }
}
public class EntityContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(@"Server=(LocalDB)\MSSQLLocalDB;Database=NestedOwnedWithinDerivedDb;Trusted_Connection=True;MultipleActiveResultSets=True;");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>().ToTable("Entity");
modelBuilder.Entity<EntityWithOwned>().HasBaseType<Entity>().OwnsOne(e => e.Data, b => b.OwnsOne(o => o.SubData));
//modelBuilder.Entity<EntityWithOwned>().HasBaseType<Entity>().OwnsOne(e => e.Data, b => b.ToTable("EntityData"));
}
}
public class Program
{
private static void Main(String[] args)
{
try
{
using ( var context = new EntityContext() )
{
context.Database.EnsureDeleted();
if ( context.Database.EnsureCreated() )
{
//context.Database.ExecuteSqlCommand("ALTER TABLE Entity ALTER COLUMN Data_SubData_Prop int NULL");
}
context.Add(new EntityWithOwned());
context.SaveChanges();
context.Add(new Entity());
context.SaveChanges(); // => SqlException: Cannot insert the value NULL into column 'Data_SubData_Prop', table 'NestedOwnedWithinDerivedDb.dbo.Entity'; column does not allow nulls. INSERT fails.
}
Console.WriteLine("Finished.");
}
catch ( Exception ex )
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
}
}
This model results in allowing NULL for columns Prop and Data_Prop but not Data_SubData_Prop:
Workarounds
So far, I found three possibilities to work around the problem:
OwnedSubData.Propcould be given typeInt32?instead ofInt32. But this would change the model only in order to deal with a flaw in EF Core. So this is not really an option.- The owned properties can be stored in a separate table (as out-commented in the code: see
ToTable("EntityData")). BTW, this would also reflect the model more closely in the sense that bothData_PropandData_SubData_Propwouldn't allow NULL whereasPropstill would. - A SQL command can be used to allow NULL after the database has been created (as out-commented in the code: see
ExecuteSqlCommand). This workaround yields the same database schema as if this issue was fixed.
However, I'm wondering whether there is a workaround that doesn't use SQL directly and doesn't introduce a new table, i.e.:
Is it possible to manually configure the database column for OwnedSubData.Prop to allow NULL by Fluent API?
(IsRequired(false) cannot be used because Int32 is not nullable.)
Further technical details
EF Core version: Microsoft.EntityFrameworkCore v2.1.2 Database Provider: Microsoft.EntityFrameworkCore.SqlServer v2.1.2 Operating system: Windows 10 IDE: Visual Studio 2017 v15.8.1
I just added a third workaround to the issue.
@AndriySvyryd to find dupe.
To repro change LeefA.LeafAAddress.Country.PlanetId to int in https://github.com/aspnet/EntityFrameworkCore/tree/release/2.2/src/EFCore.Specification.Tests/Query/OwnedQueryTestBase.cs#L300
@AndriySvyryd - I tried changing the type in the test but it caused issues with seed data and multiple cascade path. For now, I added a new test which utilizes the same model as in OP.
@smitpatel You could just restrict cascade on delete on the corresponding FK
Facing this issue with 5.0.1 with nullable reference types enabled. Here is a repro:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.1" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations" />
</ItemGroup>
</Project>
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
namespace ConsoleApp1
{
public abstract class A
{
[Key]
public int Key { get; set; }
}
public class B : A
{
}
public class C : A
{
public D D { get; set; }
}
public class D
{
public string E { get; set; }
}
public class Context : DbContext
{
public virtual DbSet<A> As { get; set; }
public virtual DbSet<B> Bs { get; set; }
public virtual DbSet<C> Cs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<A>();
modelBuilder.Entity<B>();
modelBuilder.Entity<C>(
c =>
{
c.OwnsOne(c => c.D);
});
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
The migration generated using dotnet ef migrations add has false for D.E:
using Microsoft.EntityFrameworkCore.Migrations;
namespace ConsoleApp1.Migrations
{
public partial class InitialMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "As",
columns: table => new
{
Key = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Discriminator = table.Column<string>(type: "nvarchar(max)", nullable: false),
D_E = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_As", x => x.Key);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "As");
}
}
}
@hypdeb Duplicate of https://github.com/dotnet/efcore/issues/23479, try 5.0.2
@AndriySvyryd seems to work. Thanks a lot !