Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to delete record in LINQ to Entities

I just have a very simple situation where all I need is to delete record using Linq2Entities. I tried to do some research and still can't figure out the right way to do it.

Here's my simple code:

[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();
         ctx.DeleteObject(x);
         ctx.SaveChanges();
    }
 }

[DataObjectMethod(DataObjectMethodType.Select)]
public List<Employee> GetAllEmployee()
{
    using (var ctx = new MyEntity())
    {
        var x = from y in ctx.Employees
                select y;
        return x.ToList();
    }
}

I can delete a particular record if for example I assign y.EmployeeName == "Harold Javier" to the Delete method above, but when I assign y.EmployeeId == z.EmployeeId to the above code, the delete doesn't work. (Note: EmployeeId is the primary key of the Employee table)

like image 268
Harold Javier Avatar asked Mar 18 '13 04:03

Harold Javier


People also ask

How do I delete a record in LINQ?

You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands. LINQ to SQL does not support or recognize cascade-delete operations.

How do I delete a record in Entity Framework?

Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.


1 Answers

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

like image 101
Sanket Gandhi Avatar answered Sep 23 '22 01:09

Sanket Gandhi