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
)
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.
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly