InvalidOperationException when removing an entity which shares a non-nullable foreign key with a related entity
We have an entity with two relationships, one required and one optional. These relationships share a non-nullable foreign key (they must share the key to enforce referential integrity). When we remove the optional entity, it seems EF is trying to null out the shared property even though it is still valid for the required relationship. This results in an InvalidOperationException.
Steps to reproduce
Entity Model
public class EmployeeHrRecord
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
// This is a the shared FK
public Guid EmployeeId { get; set; }
[ForeignKey("EmployeeId")]
public virtual Employee Employee { get; set; }
public Guid? EmployeeDetailId { get; set; }
[ForeignKey("EmployeeDetailId, EmployeeId")]
public virtual EmployeeDetail EmployeeDetail { get; set; }
}
public class Employee
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string Name { get; set; }
public virtual List<EmployeeDetail> EmployeeDetails { get; set; } = new List<EmployeeDetail>();
}
public class EmployeeDetail
{
// composite PK
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
// composite PK
public Guid EmployeeId { get; set; }
public string PhoneNumber { get; set; }
[ForeignKey("EmployeeId")]
public virtual Employee Employee { get; set; }
}
Program
class Program
{
static void Main(string[] args)
{
// create test data
using (var context = new MyContext())
{
var employee = new Employee { Name = "Test" };
context.Add(employee);
var employeeDetail = new EmployeeDetail { Employee = employee, PhoneNumber = "123-1234" };
employee.EmployeeDetails.Add(employeeDetail);
var employeeHrRecord = new EmployeeHrRecord { Employee = employee, EmployeeDetail = employeeDetail };
context.EmployeeHrRecord.Add(employeeHrRecord);
context.SaveChanges();
}
// Remove the optional entity
using (var context = new MyContext())
{
var hr = context.EmployeeHrRecord.First();
context.Remove(hr.EmployeeDetail);
}
}
}
Exception
The association between entities 'Employee' and 'EmployeeHrRecord' with the key value '{EmployeeId: d4428696-a123-4506-9b16-08d819e92122}' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.HandleConceptualNulls(Boolean sensitiveLoggingEnabled, Boolean force, Boolean isCascadeDelete)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.CascadeDelete(InternalEntityEntry entry, Boolean force, IEnumerable`1 foreignKeys)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
at Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry.set_State(EntityState value)
at Microsoft.EntityFrameworkCore.DbContext.Remove[TEntity](TEntity entity)
Further technical details
EF Core version: 3.1.5 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET Framework 4.8 Operating system: Windows 10 IDE: Visual Studio 2019 16.5.4
To work around this problem in our app, we added a 2-way navigation property and manually disassociated the optional entity before removing it from the context. For example:
// Remove the optional entity
using (var context = new MyContext())
{
var hr = context.EmployeeHrRecord.First();
hr.EmployeeDetail.EmployeeHrRecords.Remove(hr);
context.Remove(hr.EmployeeDetail);
context.SaveChanges();
}
@BabellDev Please post your OnModelCreating code so we can see how the entity types are configured.
@ajcvickers here is OnModelCreating from my example:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EmployeeDetail>().HasKey(x => new { x.Id, x.EmployeeId });
}
Worth mentioning: I tried explicitly changing cascade delete to "NoAction" on all relationships, but that did not prevent the exception.
The example code is from a minimal project created to demonstrate the issue we are experiencing in our large application (recently upgraded from EF6 to EFCore 3.1.5). Please let me know if you would like me to share the example project.
@BabellDev Yes, please attach the minimal project.
@ajcvickers here is the sample project, thanks. EFCore.SeveredKeyExample.zip
@BabellDev Thanks--I was able to repro.
Note for team: the issue is still present in 5.0 preview 6 and not limited to lazy-loading proxies. Model:
Model:
EntityType: Employee
Properties:
Id (Guid) Required PK AfterSave:Throw ValueGenerated.OnAdd
Name (string)
Navigations:
EmployeeDetails (List<EmployeeDetail>) Collection ToDependent EmployeeDetail Inverse: Employee PropertyAccessMode.Field
Service properties:
LazyLoader (no field, ILazyLoader)
Keys:
Id PK
EntityType: EmployeeDetail
Properties:
Id (Guid) Required PK AfterSave:Throw ValueGenerated.OnAdd
EmployeeId (Guid) Required PK FK Index AfterSave:Throw
PhoneNumber (string)
Navigations:
Employee (Employee) ToPrincipal Employee Inverse: EmployeeDetails PropertyAccessMode.Field
Service properties:
LazyLoader (no field, ILazyLoader)
Keys:
Id, EmployeeId PK
Foreign keys:
EmployeeDetail {'EmployeeId'} -> Employee {'Id'} ToDependent: EmployeeDetails ToPrincipal: Employee Cascade
Indexes:
EmployeeId
EntityType: EmployeeHrRecord
Properties:
Id (Guid) Required PK AfterSave:Throw ValueGenerated.OnAdd
EmployeeDetailId (Nullable<Guid>) FK Index
EmployeeId (Guid) Required FK Index
Navigations:
Employee (Employee) ToPrincipal Employee PropertyAccessMode.Field
EmployeeDetail (EmployeeDetail) ToPrincipal EmployeeDetail PropertyAccessMode.Field
Service properties:
LazyLoader (no field, ILazyLoader)
Keys:
Id PK
Foreign keys:
EmployeeHrRecord {'EmployeeId'} -> Employee {'Id'} ToPrincipal: Employee Cascade
EmployeeHrRecord {'EmployeeDetailId', 'EmployeeId'} -> EmployeeDetail {'Id', 'EmployeeId'} ToPrincipal: EmployeeDetail ClientSetNull
Indexes:
EmployeeId
EmployeeDetailId, EmployeeId
This is fixed in EF Core 6.0 preview 7. Likely same root cause as #23883 and/or #23757.
Change tracker before Remove:
EmployeeHrRecord {Id: 3c693fcd-a62b-458c-17fa-08d9660eda80} Unchanged
Id: '3c693fcd-a62b-458c-17fa-08d9660eda80' PK
EmployeeDetailId: 'a074edda-ac84-4c66-8723-08d9660eda81' FK
EmployeeId: '668c5fe6-28f5-4799-29f8-08d9660eda7a' FK
Employee: <null>
EmployeeDetail: <null>
After lazy-load and remove:
EmployeeDetail {Id: a074edda-ac84-4c66-8723-08d9660eda81, EmployeeId: 668c5fe6-28f5-4799-29f8-08d9660eda7a} Deleted
Id: 'a074edda-ac84-4c66-8723-08d9660eda81' PK
EmployeeId: '668c5fe6-28f5-4799-29f8-08d9660eda7a' PK FK
PhoneNumber: '123-1234'
Employee: <null>
EmployeeHrRecord {Id: 3c693fcd-a62b-458c-17fa-08d9660eda80} Modified
Id: '3c693fcd-a62b-458c-17fa-08d9660eda80' PK
EmployeeDetailId: <null> FK Modified Originally 'a074edda-ac84-4c66-8723-08d9660eda81'
EmployeeId: '668c5fe6-28f5-4799-29f8-08d9660eda7a' FK
Employee: <null>
EmployeeDetail: <null>
After SaveChanges:
EmployeeHrRecord {Id: b80f0a05-85c0-48e1-3b26-08d9660f70f7} Unchanged
Id: 'b80f0a05-85c0-48e1-3b26-08d9660f70f7' PK
EmployeeDetailId: <null> FK
EmployeeId: '2d12f06e-42c1-445b-f234-08d9660f70f1' FK
Employee: <null>
EmployeeDetail: <null>