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
: 7630 At:- 12/19/2017 12:54:11 PM
C# Entity-framework Delete a single record using EF sql-server







2 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();

You can use 'SingleOrDefault' instead of 'FirstOrDefault' in above C# Code, for safer output.

4
At:- 12/20/2017 6:56:49 AM Updated at:- 11/22/2022 5:52:27 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


profileImage Answered by:- vikas_jk

You can also have generic method to delete single record using Entity framework

public virtual void DeleteSingleRecord<T>(int id) where T : BaseEntity, new()
{
    T instance = Activator.CreateInstance<T>();
    instance.Id = id;
    if (dbContext.Entry<T>(entity).State == EntityState.Detached)
    {
        dbContext.Set<T>().Attach(entity);
    }

    dbContext.Set<T>().Remove(entity);
}

That should work.

0
At:- 11/22/2022 11:06:15 AM






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