Entity Framework - Delete Single Entity


Delete single entity in connected scenario:-

Steps to delete single entity
1. Get the requested  record.
2. Call DeleteObject of Employees entity.
3. Finally call to SaveChanges method that will delete the employess record from the database.
using (var ctx = new EFSourceDBContext())
{
    //1. Get the requested record
    var emp = (from e in ctx.Employees
                where e.EmpId == 10
                select e).FirstOrDefault();

    //2. DeleteObject call
    ctx.Employees.DeleteObject(emp);
    
    //3. SaveChanges method call.
    int num = ctx.SaveChanges();
}

Delete single entity in Disconnected scenario:-

Steps to delete single entity
1. Create Employee object.
2. Get the requested record in in the object.
3. Attach the emp entity object in Employees entity.
4. Call DeleteObject of Employees entity.
5. Finally call to SaveChanges method that will delete the employess record from the database.

Employee emp = null;
using (var ctx = new EFSourceDBContext())
{
    emp = (from e in ctx.Employees
            where e.EmpId == 10
            select e).FirstOrDefault();
}

using (var dbctx = new EFSourceDBContext())
{
    dbctx.Employees.Attach(emp);
    dbctx.Employees.DeleteObject(emp);
    //OR can be deleted using ObjectStateManager also 
    //dbctx.ObjectStateManager.ChangeObjectState(emp, System.Data.EntityState.Deleted);
    int num = dbctx.SaveChanges();
}

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More