Entity frame work Remove, RemoveRange and EntityState Deleted

c# entity-framework entity-framework-6

Question

What distinguishes these three lines from one another?

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 test every strategy, and I stick with the ones that work for me. But honestly I don't understand the concept here

1
0
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.Books.RemoveRange(booksToRemove);
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.

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