Entity frame work Remove, RemoveRange and EntityState Deleted

c# entity-framework entity-framework-6

Question

What is the difference between these three lines

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

 courses.ForEach(currentCourse =>
                        {

First

_context.CustomerCourses.RemoveRange(currentCourse.AssignedCustomers);

Second

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

Third

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

                        });
        }

When to use what and in which scenario? I always stuck to identify which one should be used. I try every approach whichever works for me I keep it. But honestly I don't understand the concept here

1
0
8/28/2018 8:12:42 PM

Popular Answer

The Remove Range() method is used to remove a collection or a list within entity framework. This is a better alternative to using a loop to iterate over the collection and set the entity state of the object 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.Books.RemoveRange(booksToRemove);
context.SaveChanges(); }

In the above example, RemoveRange(booksToRemove) sets the state of all the entities of the list "booksToRemove" as deleted and performs a DELETE command for all the entities on context.SaveChanges().

RemoveRange is an alternative method that you can use instead of the second and third option posted above. It is recommended to use RemoveRange and AddRange for deleting and inserting a large number of records using entity framework.

1
8/28/2018 8:28:51 PM


Related Questions





Related

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