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
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.
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.
You can use RemoveRange : context. MY_GROUPS. RemoveRange(context.
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.
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;
}
}
Just use
db.Entry(query_D).State = System.Data.EntityState.Deleted;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With