Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entity framework delete record

I am trying to delete record from table store but I having problem of recognizing DeleteObject in my code. I have reference

using System.Linq;
using System.Data.Entity;
using System.Data.Objects;

but it still not working. I am using MVC 4 using Visual Studio 2012.

public void Delete()
{
    using (var db = new AppContext())
    {
        var query_D = (from b in db.Stores
                   where b.storeID == 1
                   select b).First();

        db.DeleteObject(query_D);
        db.SaveChanges();
    } 
}

thanks in advance

like image 544
K.Z Avatar asked Jan 29 '13 13:01

K.Z


People also ask

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.

How do I delete a single record?

The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in the WHERE clause. DELETE FROM table_name WHERE some_condition; table_name: name of the table some_condition: condition to choose particular record.

How do I delete a list in Entity Framework?

You can use RemoveRange : context. MY_GROUPS. RemoveRange(context.

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.


2 Answers

I realized that you're using the MVC 4 with VS2012, and by default the Entity Framework version is 5.

Now the way you delete is from EF4.

Here's the proper way to delete using the EF5

using (var db= new AppContext(ConnectionStr))
{
    try
    {
        con.Configuration.AutoDetectChangesEnabled = false;
        var o = new Store { Id = 1 };
        db.Stores.Attach(o);
        db.Stores.Remove(o);
        db.SaveChanges();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.InnerException.Message);
    }
    finally
    {
        con.Configuration.AutoDetectChangesEnabled = true;
    }
}
like image 194
spajce Avatar answered Sep 18 '22 18:09

spajce


Just use

db.Entry(query_D).State = System.Data.EntityState.Deleted;
like image 37
Jan P. Avatar answered Sep 19 '22 18:09

Jan P.