The easiest way to delete an object using Entity Framework 4

Ack! I am new to Entity Framework and trying to find the easiest way to remove an item.

I have a list with a data source set for TagCategory objects from a database. This is working fine. Now I want to delete the selected item. So I am doing something like this:

TagCategory category = (TagCategory)lstCategories.SelectedItem; using (MyEntities context = new MyEntities()) { context.AttachTo("TagCategories", category); context.DeleteObject(category); context.SaveChanges(); } 

It seems straightforward enough, but it will not work. Nothing deleted, no error message, nothing.

So, I see that I can do something like this instead:

 using (MyEntities context = new MyEntities()) { string cmd = String.Format("DELETE FROM TagCategory WHERE TagCatID=@ID ", category.TagCatID)); context.ExecuteStoreCommand(qry); } 

It seems to work. So am I just going with what works, or can Entity Framework 4 do it?

EDIT: Nevermind. In fact, I had another problem that prevented the execution of the code form. Both published snippets seem to work fine. My apologies.

+4
source share
3 answers

You can use a stub object, something like this:

 using (var context = new MyEntities()) { var tagCategory = new TagCategory { PostId = category.TagCatID }; context.TagCategories.Attach(tagCategory); context.DeleteObject(tagCategory); context.SaveChanges(); } 
+6
source

I'm not sure if you can use AttachTo() for this. Depends on how you populated the ListBox.

What should work:

  var Key = context.CreateEntityKey("TagCategory", category); Object original; if (context.TryGetObjectByKey(Key, out original)) { context.DeleteObject(original); context.SaveChanges(); } 
+2
source
 // using the Find method of DBContext to retrieve the record you wish to delete // works for me // below code taken from a working WPF application using sdf database if (this.TransactionsDataGrid.SelectedIndex > -1) { Transaction transaction = this.TransactionsDataGrid.SelectedItem as Transaction; if (transaction != null) { using (BilliEntities context = new BilliEntities()) { try { Transaction trans = context.Transactions.Find(transaction.TransactionId); if (trans != null) { // observable collection for datagrid this.Transactions.Remove(transaction); context.Transactions.Remove(trans); context.SaveChanges(); } } catch (Exception ex) { // for debugging } } } } 
0
source

Source: https://habr.com/ru/post/1336870/


All Articles