使用 Entity Framework 4 删除对象的最简单方法
确认!我是实体框架的新手,正在尝试找到删除项目的最简单方法。
我有一个列表框,其数据源设置为数据库中的 TagCategory 对象。这工作正常。现在我想删除所选项目。所以我做了这样的事情:
TagCategory category = (TagCategory)lstCategories.SelectedItem;
using (MyEntities context = new MyEntities())
{
context.AttachTo("TagCategories", category);
context.DeleteObject(category);
context.SaveChanges();
}
这看起来很简单,但它不起作用。没有删除任何内容,没有错误消息,什么也没有。
所以我发现我可以做这样的事情:
using (MyEntities context = new MyEntities())
{
string cmd = String.Format("DELETE FROM TagCategory WHERE TagCatID=@ID",
category.TagCatID));
context.ExecuteStoreCommand(qry);
}
这似乎有效。那么我是只选择有效的方法,还是 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定您是否可以使用
AttachTo()
来实现此目的。取决于您如何填充列表框。什么应该起作用:
I'm not sure you can use
AttachTo()
for this. Depends on how you filled the ListBox.What ought to work:
您可以使用存根实体,如下所示:
You can use stub entity, something like this: