CodexBloom - Programming Q&A Platform

Entity Framework Core 6: how to to Insert Related Entities with Cascade Delete Configured

πŸ‘€ Views: 90 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
entity-framework-core ef-core csharp

I'm working on a project using Entity Framework Core 6, and I'm working with an scenario when trying to insert a parent entity along with its related child entities. I've set up my models so that deletions cascade correctly, but when I attempt to add a new parent that includes child entities, I get an `InvalidOperationException` stating that 'The operation failed because the DbContext is not tracking the entity.' This happens even though I'm properly attaching the child entities before saving. Here’s a simplified version of my code: ```csharp public class Parent { public int Id { get; set; } public string Name { get; set; } public ICollection<Child> Children { get; set; } = new List<Child>(); } public class Child { public int Id { get; set; } public string ChildName { get; set; } public int ParentId { get; set; } public Parent Parent { get; set; } } var parent = new Parent { Name = "Parent A" }; parent.Children.Add(new Child { ChildName = "Child A1" }); parent.Children.Add(new Child { ChildName = "Child A2" }); using (var context = new MyDbContext()) { context.Parents.Add(parent); await context.SaveChangesAsync(); // Exception occurs here } ``` I’ve also double-checked my DbContext configuration, and I've configured cascade deletes for the relationship: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Parent>() .HasMany(p => p.Children) .WithOne(c => c.Parent) .OnDelete(DeleteBehavior.Cascade); } ``` I tried explicitly marking the children as added by calling `context.Entry(child).State = EntityState.Added;`, but it didn't resolve the scenario. Could this be a question with how I'm setting up the relationships, or is there something else I'm missing with the DbContext tracking? Any help would be appreciated!