简体   繁体   中英

Simplest Way to Delete Object with Entity Framework 4

Ack! I'm new to Entity Framework and am trying to find the simplest way to delete an item.

I have a listbox with the datasource set to TagCategory objects from the database. This is working fine. Now I'd like to delete the selected item. So I do something like this:

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

This seems straight forward enough, but it doesn't work. Nothing is deleted, no error message, nothing.

So I see I can instead do something like this:

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

That seems to work. So do I just go with what works, or is Entity Framework 4 actually capable of doing this?

EDIT: Nevermind. In fact, I had another issue that prevented the code form executing. Both snippets I posted seem to work okay. My apologies.

You can use stub entity, something like this:

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

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

What ought to work:

  var Key = context.CreateEntityKey("TagCategory", category);
  Object original;
  if (context.TryGetObjectByKey(Key, out original))
  {
        context.DeleteObject(original);
        context.SaveChanges();
  }
// 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
           }
        }
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM