How to delete a single Record using Entity Framework?


How can I delete (remove) single record from database table using entity framework in asp.net MVC Controller?

please note I want to delete row of selected Id from the database permanently(Not to make a column IsActive and set it as false)


Asked by:- Sam
1
: 387 At:- 12/19/2017 12:54:11 PM
C# Entity-framework Delete a single record using EF sql-server






1 Answers
profileImage Answered by:- Vipin

You can delete the single record using Entity framework by selecting that record first and then using .Remove () method

using (var Context= new DataBaseEntities())
{
var itemToRemove = Context.Table_Name.Where(a => a.id == 1).FirstOrDefault(); //returns a single item.

if (itemToRemove != null) {
    Context.Table_Name.Remove(itemToRemove);
    Context.SaveChanges();
}
}

Or you can use context.Entry(employer).State = EntityState.Deleted

using (var Context= new DataBaseEntities())
{
var itemToRemove = Context.Table_Name.Where(a => a.id == 1).FirstOrDefault(); //returns a single item.

if (itemToRemove != null) {
    Context.Entry(itemToRemove).State = EntityState.Deleted;
    Context.SaveChanges();
}
}

Or

 var ObjectTORemove= Context.Table_Name.Where(a => a.id == 1).FirstOrDefault();

  //Delete it from memory
  entities.DeleteObject(ObjectTORemove);
  //Save to database
  entities.SaveChanges();

4
At:- 12/20/2017 6:56:49 AM
thanks, @vipin, I have tried the first method only and it worked 0
By : Sam - at :- 12/25/2017 1:08:39 PM
Deleting single object using 1st method in Entity framework works for me 0
By : Vinnu - at :- 1/4/2018 2:46:00 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use