Entity Framework: delete list of child objects from parent

时间:2017-08-04 12:56:54

标签: c# entity-framework foreign-keys parent-child delete-row

I basically have a pretty simple setup of a one-to-many parent-child relationships. E.g.: public class Parent { public Guid Id { get; set; } public virtual ICollection<Child> Children { get; set; } } public class Child { public Guid Id { get; set; } public Guid ParentId { get; set; } public virtual Parent Parent { get; set; } } This is configured using FluentValidation as: public ChildConfiguration() { ToTable("children"); HasKey(c => c.Id); Property(c => c.Id).HasColumnName("id"); HasRequired(c => c.Parent).WithMany(p => p.Children); } I now have an API that provides the list of children for a parent, but I don't want to add the list of children to the existing list every time. Instead I want to delete all existing children to replace them with the list of new ones. I tried doing so by fetching the parent, clearing the current list of children and adding the new ones. var parent = await _repository.GetById(parentId); parent.Children.Clear(); foreach (var child in children) { parent.Children.Add(child); } This does not work, as it throws an exception: 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. As I understood this is because it's trying to remove the link between the two entities rather than actually deleting it from the database. A solution is to directly access the Children in the DbContext and do a RemoveRange as: DbContext.Children.RemoveRange(children); But I don't want to expose my Children entity directly on the context. Instead I always want to go through the Parent. So I could create a method in the repository like: var parent = DbContext.Parents.Find(parentId); foreach (var child in parent.Children.ToList()) { parent.Remove(child); } But this is throwing the same exception and I don't understand why as I think I am explicitly telling EF to remove the child from the parent. Is there a way to remove the children from the DB without accessing them directly on the DbContext? Thanks!

1 个答案:

答案 0 :(得分:-1)

Guid 是一个struct和struct是非可空类型,就像基本类型一样。 例如: int double bool 等......

您可以使用以下代码删除给定父级的子级

var parent = await _repository.GetById(parentId);
parent.Children.Clear();
foreach (var child in children)
{
     parent.Children.Add(child);
}

通过声明您的 Guid ParentId 属性,子类 Nullable ,例如 Nullable&lt; Guid &gt;