Entity Framework Tutorial Basics(25):Delete Single Entity

追憶似水流年發表於2016-07-07

Delete Entity using DBContext in Disconnected Scenario:

We used the Entry() method of DbContext to mark EntityState as Modified in the previous chapter. In the same way, we can use the Entry() method to attach a disconnected entity to the context and mark its state to Deleted.

Student studentToDelete;
//1. Get student from DB
using (var ctx = new SchoolDBEntities())
{
    studentToDelete = ctx.Students.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();
}

//Create new context for disconnected scenario
using (var newContext = new SchoolDBEntities())
{
    newContext.Entry(studentToDelete).State = System.Data.Entity.EntityState.Deleted;    

    newContext.SaveChanges();
}

 

The code shown above results in the following delete query which deletes the row from Teacher table.

delete [dbo].[Student]
where ([StudentId] = @0)',N'@0 int',@0=1

 

Thus, you can delete a single entity in disconnected scenario.

相關文章