首页 > 解决方案 > 实体框架 Remove、RemoveRange 和 EntityState Deleted

问题描述

这三行有什么区别

var courses = _context.Courses
                                      .Include("AssignedCustomers")
                                      .Include("PricingSchedule")
                                      .Include("Licenses")
                                      .Include("GroupCourses")
                                      .Include("GroupLicenses")
                                      .Where(e => courseIds.Contains(e.Id)).ToList();

 courses.ForEach(currentCourse =>
                        {

第一的

_context.CustomerCourses.RemoveRange(currentCourse.AssignedCustomers);

第二

 currentCourse.AssignedCustomers.ToList().ForEach(ac =>
                        {
                            _context.Entry(ac).State = EntityState.Deleted;
                        });

第三

currentCourse.AssignedCustomers.ToList().ForEach(ac =>
                        {
                            currentCourse.AssignedCustomers.Remove(ac);

                        });
        }

何时使用什么以及在哪种情况下使用?我总是坚持确定应该使用哪一个。我尝试所有对我有用的方法,我保留它。但老实说,我不明白这里的概念

标签: c#entity-frameworkentity-framework-6

解决方案


Remove Range() 方法用于删除实体框架内的集合或列表。这是使用循环遍历集合并将对象的实体状态设置为已删除的更好选择。

IList<Book> booksToRemove = new List<Book>() {
                                new Book() { BookId = 1, BookName = "Rich Dad Poor Dad" };
                                new Book() { BookId = 2, BookName = "The Great Gatsby" };
                                new Book() { BookId = 3, BooktName = "The Kite Runner" };
                            };
using (var context = new LibraryDBEntities()) {
context.Books.RemoveRange(booksToRemove);
context.SaveChanges(); }

在上面的示例中,RemoveRange(booksToRemove) 将列表“booksToRemove”的所有实体的状态设置为已删除,并对 context.SaveChanges() 上的所有实体执行 DELETE 命令。

RemoveRange 是一种替代方法,您可以使用它代替上面发布的第二个和第三个选项。建议使用 RemoveRange 和 AddRange 使用实体框架删除和插入大量记录。


推荐阅读