Deleting a disconnected entity is easy. Just set its state to Delete using the Entry()
method, as shown below.
// disconnected entity to be deleted var student = new Student(){ StudentId = 1 }; using (var context = new SchoolDBEntities()) { context.Entry(student).State = System.Data.Entity.EntityState.Deleted; context.SaveChanges(); }
In the above example, an instance of the Student
entity contains only the StudentId
key property. To delete an entity, it only requires a key property.
context.Entry(student).State = System.Data.Entity.EntityState.Deleted
attaches an entity to a context and sets its state to Deleted.
This will execute the following DELETE command in the database.
delete [dbo].[Student] where ([StudentId] = @0)',N'@0 int',@0=1