adsense

Sunday, May 30, 2021

ASP.NET MVC delete multiple records

 When it comes to deleting multiple records in ASP.NET MVC, you have two options,

 1. Connected mode

using (CourseContext db = new CourseContext())
    {
 
        List<Course> courses = db.Courses.Take(5).ToList();

        try
        { 

           db.Courses.RemoveRange(courses);
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
  

2. Disconnected mode

ListCourse> courses = new List<Course>();
courses.Add(new Course { CourseID = 1 });
courses.Add(new Course{ CourseID = 2 });
 
using (CourseContext db = new CourseContext())
    {
  
        try
        {

            db.Entry(Course).State= System.Data.Entity.EntityState.Deleted;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
 
    }


Cheers,

Samitha

No comments:

Post a Comment