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.

相关文章:

  • 2022-01-05
  • 2021-08-31
  • 2021-07-04
  • 2021-10-14
  • 2021-08-07
  • 2022-02-08
  • 2022-01-04
  • 2021-07-05
猜你喜欢
  • 2022-01-19
  • 2021-09-30
  • 2021-07-11
  • 2021-09-13
  • 2021-07-21
  • 2021-05-16
  • 2022-01-06
相关资源
相似解决方案