Proper way to delete record in LINQ to Entities

@Harold, I know this post is quite old, but I feel it is important to address your original question and answer. Your solution may have worked in your situation, but there are a couple of problems.

First, your original code was selecting the record to delete based on a passed in parameter. Your solution is deleting the record with the largest EmployeeId. That might be what you wish, but not likely. The second issue is that two database accesses are required to accomplish the delete. The first is get the entity to delete the second to actually perform the delete.

The following code snippet will eliminate the need to to the read and will delete employee "z". This should yield the desired result and perform much better.

public void DeleteEmployeeId(Employee z)
{
    using (var ctx = new MyEntityContext())  
    {  
        var x = new Employee{ EmployeeId = z.EmployeeId };
        ctx.Entry(x).State = EntityState.Deleted;  
        ctx.SaveChanges();  
    }
}

I think this is better option of delete

using (var ctx = new MyEntity())
    {
        var x = (from y in ctx.Employees
             orderby  y.EmployeeId descending
             select y).FirstOrDefault();
        ctx.Employees.Remove(x);
        ctx.SaveChanges();
    }

at my side DeleteObject is not working so i use Remove


you first need to verify that if a record exists before you actually delete it;

[DataObjectMethod(DataObjectMethodType.Delete)]

    public void DeleteEmployee(Employee z)
    {
        using (var ctx = new MyEntity())
        {
            var x = (from y in ctx.Employees
                     where  y.EmployeeId == z.EmployeeId
                     select y).FirstOrDefault();
             if(x!=null)
             {
             ctx.Employees.DeleteObject(x);
             ctx.SaveChanges();
             }
        }
     }

Always check for nulls, before you delete something. Because a user may change the Id (at querystring) and try different combinations.


The above answer may be outdated... The DeleteObject method does not seem to exist in the current version of ENtity Framework. I had to use the Remove method.

var delobj = db.mytable.Where(p => p.ServiceLocation == serviceLocationID).SingleOrDefault();
db.myTable.Remove(delobj);