简体   繁体   English

ASP MVC 5-从父级删除子级实体

[英]ASP MVC 5 - Remove Child Entities From Parent

How can I remove All child entities from a one to many relationship via the parent - Note I only want to remove the children. 如何通过父级从一对多关系中删除所有子级实体-注意,我只想删除子级。

public class Parent
{
    public int Id { get; set; }
    public ICollection<Child> Children { get; set; }
}

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

    public virtual Parent Parent { get; set; }
}

Is there a shorthand way, lets say something like below: 有没有一种简便的方法,让我们说以下话:

 parent.children.Remove();

I believe that your mechanism for deleting the child elements in EF 4 and above should be: 我相信您在EF 4及更高版本中删除子元素的机制应为:

parent.children.ToList().ForEach(c => context.Children.Remove(c));
context.SaveChanges();

I have found in the past that it may be faster to write a DELETE yourself, but you should decide what is best for you. 过去,我发现自己编写DELETE 可能会更快,但是您应该确定最适合自己的方法。 Introducing a SQL DELETE in an Entity Framework solution adds some complexity both to testing and because your DELETE will depend on things you may have been trying to avoid as EF takes care of it all. 在Entity Framework解决方案中引入SQL DELETE既增加了测试的复杂性,又因为DELETE将取决于您可能试图避免的事情,因为EF会全力以赴。 Always measure before you optimize and decide what trade-offs work for you. 在进行优化之前,请务必进行衡量并确定哪些折衷方案对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么以及如何修复子实体的 ASP MVC model 验证而不是父实体? - Why and how to fix ASP MVC model validation for child entities is called but not for parent entity? 如何在 Entity Framework Core 中的父更新时从父集合中删除子实体? - How to remove child entities from parent collection on parent update in Entity Framework Core? 从ASP.NET MVC中的子级访问父级模型数据 - Access parent model data from child in ASP.NET MVC 从父实体更新子实体 - Update child entities from parent entity 使用来自选择元素 ASP.NET Core MVC 的属性保存父项和子项 - Saving parent item and child items with properties from select element ASP.NET Core MVC 在ASP.NET MVC 4视图中将数据从父窗口传递到popup(child)窗口 - Passing data from parent window to popup(child) window in ASP.NET MVC 4 View 如何在EF中合并其父实体的子集合? - How to Union child collections from their parent entities in EF? 如何从 EF Core 中的父实体中删除子项? - How do you delete Child from Parent entities in EF Core? 从父编辑表单更新多个子实体? - Updating Multiple Child Entities from a Parent Edit Form? 银光; 从父项移除子项元素 - Silverlight; Remove a child element from a parent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM