How do i delete single record from table using EF 6.1.1

code-first ef-code-first entity-framework

Accepted Answer

Between EF 4 and EF 6, there are no changes to how to delete an object. When utilizing Entity Framework, you must utilize the delete entity method.Remove approach onDbSet . Remove both existing entities and newly added ones work.

  • Calling Remove the insertion of an entity that has been added but not yet saved to the database will be canceled. The object is eliminated from the change tracker and is no longer being monitored byDbContext .

  • Calling Remove When a change to an existing entity is tracked, the entity will be marked for deletion the following time.SaveChanges is called.

deleting and database loading simultaneously

In order to delete an existing entity, you must first load it from your context, as in the example you provided in your query. If you are unaware of theId , you can run the following query to find it first:

    var report= (from d in context.StudentReportDetail
               where d.ReportName == "Report"
               select d).Single();


deletion prior to database loading

It's a little inefficient to obtain an entity from the database only to remove it if you need to destroy it but it's not already in memory. You can attach a stub that represents the entity to be deleted and then delete this stub if you know the key to the object you want to destroy. An instance of an entity with only the key value assigned is called a stub. For deleting entities, only the key value is needed..

var toDelete = new StudentReportDetail {Id = 2 };


Another option is to alter the entity's state toDeleted .DbContext has techniques known asEntry and Entry<TEntity> these techniques receive aDbEntityEntry for the specified entity, grant access to the entity's data, and return aDbEntityEntry item capable of acting upon the entity. By simply switching the entity status to "deleted," you can now delete the context.EntityState.Deleted :

var toDelete = new StudentReportDetail {Id = 2 };
context.Entry(toDelete).State = EntityState.Deleted;  

using an outside library

A third option, which uses a third-party library called Plus EntityFramework, is available as a nugget package that you may install. The batch delete procedure can be used to:

    .Where(u => u.Id== stuDetails)
8/9/2017 2:37:01 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow