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();
}
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