Entity frame work Remove, RemoveRange and EntityState Deleted

c# entity-framework entity-framework-6


What distinguishes these three lines from one another?

var courses = _context.Courses
                                      .Where(e => courseIds.Contains(e.Id)).ToList();

 courses.ForEach(currentCourse =>




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


currentCourse.AssignedCustomers.ToList().ForEach(ac =>


When to use what and in which scenario? I always stuck to identify which one should be used. I test every strategy, and I stick with the ones that work for me. But honestly I don't understand the concept here

8/28/2018 8:12:42 PM

Popular Answer

Within the entity framework, a collection or a list may be eliminated using the Remove Range() function. This is a better option than using a loop to traverse over the collection and change the object's entity state to Deleted.

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.SaveChanges(); }

In the example above, RemoveRange(booksToRemove) executes a DELETE command for each entity on context and changes the status of every entity in the list "booksToRemove" to removed. SaveChanges().

You may use RemoveRange as a substitute for the second and third options mentioned above. When utilising entity framework to delete and add a lot of data, it is advised to utilise RemoveRange and AddRange.

8/28/2018 8:28:51 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow