entity framework delete record

asp.net-mvc entity-framework linq

Question

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

1
5
2/5/2014 3:25:02 PM

Accepted Answer

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;
    }
}
9
2/5/2014 3:33:25 PM

Popular Answer

Just use

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow