Tip: EF CodeFirst – Deleting child records

Error Message

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

Solution

Have you ever encountered problems in deleting the child records? One team member from my team got that problem a couple of months back.. The only solution that I found is that you need to change the state of child object to “Deleted” instead of using “Remove()” function. The code below is to show you how to delete the child records. Please focus on “DeleteAllChildren()”. Please let me know if you have a better solution for this issue. Thanks!

public class TestDbContext : DbContext
{
public DbSet Parent { get; set; }
}

public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection Children { get; set; }
}

public class Child
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
}

private static void DeleteAllChildren()
{
var context = new TestDbContext();

var existingRecord = context.Parent.Include(c => c.Children).First();

for (var i = existingRecord.Children.Count - 1; i >= 0;i-- )
{
var child = existingRecord.Children.ElementAt(i);
var dbEntity = context.Entry(child);
dbEntity.State = System.Data.EntityState.Deleted;
}

context.SaveChanges();

Console.WriteLine("Done");
Console.ReadLine();
}

private static void Create()
{
var parent = new Parent()
{
Name = "M",
Children = new Collection{
new Child (){ Name ="A"},
new Child (){ Name ="B"}
}
};

var context = new TestDbContext();
context.Parent.Add(parent);

context.SaveChanges();
}
var context = new TestDbContext();
var first = context.Parent.First();
context.Parent.Remove(first);
context.SaveChanges();

4 thoughts on “Tip: EF CodeFirst – Deleting child records

  1. Might make more sense to use
    foreach(var child in existing.Children)
    context.Entry(child).State=EntityState.Deleted;
    But the term you’re looking for is called a cascade delete.

  2. @Anonymous I will get back to you on this.

    @Eric

    No.. It’s not “Cascade delete”.. I dont want to delete the parent. just want to delete only children.

Leave a Reply

Your email address will not be published. Required fields are marked *