繁体   English   中英

使用实体框架4删除对象的最简单方法

[英]Simplest Way to Delete Object with Entity Framework 4

确认! 我是Entity Framework的新手,我正在尝试找到删除项目的最简单方法。

我有一个列表框,数据源设置为数据库中的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);
}

这似乎有效。 那么我只是去做有用的,或者实体框架4实际上能够做到这一点?

编辑:没关系。 事实上,我有另一个问题阻止代码表单执行。 我发布的两个片段似乎都运行正常。 我很抱歉。

您可以使用存根实体,如下所示:

using (var context = new MyEntities())
{
     var tagCategory = new TagCategory
     {
         PostId = category.TagCatID
     };
     context.TagCategories.Attach(tagCategory);
     context.DeleteObject(tagCategory);
     context.SaveChanges();
}

我不确定你可以使用AttachTo() 取决于你如何填充ListBox。

什么应该工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM