最简单的方法来删除对象与实体框架4 [英] 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.
我有一个数据源设置为从数据库TagCategory对象列表框。这是工作的罚款。现在我想删除选定的项目。所以,我做这样的事情:
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);
}
这似乎工作。所以,不要我去什么工作,或者是实体框架4居然能够做到这一点?
That seems to work. So do I just go with what works, or is Entity Framework 4 actually capable of doing this?
编辑:没关系。其实,我有另一个问题,prevented的code形式执行。这两个片段我张贴似乎工作好。我的道歉。的
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();
}
这篇关于最简单的方法来删除对象与实体框架4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!