Delete entry

I am trying to delete a record from a table store, but I have a recognition problem DeleteObjectin my code. I have a link

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

but it still does not work. I use MVC 4using 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();
    } 
}

early

+5
source share
3 answers

I realized that you are using MVC 4 with VS2012, and the default version of Entity Framework is 5.

Now how are you deletefrom EF4.

Here is the correct way deletewithEF5

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;
    }
}
+9
source

Just use

db.Entry(query_D).State = System.Data.EntityState.Deleted;
+8
source

You must try:

db.Stores.Remove(query_D);
db.SaveChanges();
0
source

All Articles