开发者

Simplest Way to Delete Object with Entity Framework 4

开发者 https://www.devze.com 2023-02-07 00:49 出处:网络
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

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
           }
        }
     }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消