Description
openedon Apr 5, 2021
I think there is a bug when updating entities with UPDATE DbContext method with nulled complex types.
Steps to reproduce
If you have these classes:
public class User {
public string Identifier { get; set; }
public Class2 Child { get; set; }
}
public class Class2 {
public string Name { get; set; }
public Class3 Surnames { get; set; }
}
public class Class3 {
public string Surname1 { get; set; }
public string Surname2 { get; set; }
}
Modeled with EF Core as follows:
modelBuilder.Entity<User>().HasKey(t => t.Identifier);
modelBuilder.Entity<User>().OwnsOne(_ => _.Child).Property(_ => _.Name).IsRequired(false);
modelBuilder.Entity<User>().OwnsOne(_ => _.Child).OwnsOne(_ => _.Surnames);
Now you insert an object with these values:
{
"User": {
"Identifier": "TESTID",
"Child": {
"Name": "NAME1",
"Surnames": {
"Surname1": "SUR1",
"Surname2": "SUR2"
}
}
}
}
Row in Database:
Identifier = TESTID,
Name = Name1,
Surname1 = SUR1,
Surname2= SUR2
Actual behaviour
I want to update my object to these values:
"User": {
"Identifier": "TESTID",
"Child": {
"Name": "NAMEMODIFIED",
"Surnames": null
}
}
I want to update whole object in all cases, so I use:
public void Update(User entity) {
this.context.Users.Update(entity);
this.context.SaveChanges();
}
I don't want to find the entity in the database as it is not necessary in my case. So, Update method marks recursively as modified all properties, and that is the behaviour that I want.
This works perfectly with all properties (nested and owned included) except in cases where an Owned entity is NULL, as it ignores it and leaves the value it had in the database, instead of updating it to NULL.
Row in DB after update
Identifier = TESTID,
Name = NAMEMODIFIED,
Surname1 = SUR1,
Surname2= SUR2
Expected Row in DB after update
Identifier = TESTID,
Name = NAMEMODIFIED,
Surname1 = null,
Surname2= null
Include provider and version information
EF Core version: 5.0.4
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: .NET Core 3.1
Operating system: Windows 10
IDE: Visual Studio 2019 16.4.0