Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 981
Jonathan Wood Avatar asked Feb 25 '23 07:02

Jonathan Wood


1 Answers

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();
}
like image 173
Kris Ivanov Avatar answered Mar 07 '23 11:03

Kris Ivanov