【问题标题】:Delete Db element with EntityFrameWork使用 EntityFrameWork 删除 Db 元素
【发布时间】:2012-04-30 15:56:46
【问题描述】:

我正在尝试实现一种删除数据库表元素的方法。

下面的代码没有抛出任何异常,但是执行后该元素仍然存在于表格中。

namespace SuitTest_tt_content_2
{
    class DBUtils
    {
        public static StandardResponse checkContent(long id)
        {
            using (OnlineRedesignIndexEntities DB = new OnlineRedesignIndexEntities())
            {
                try
                {
                    Console.WriteLine("          ************** TEST ADD_CONTENT **************          ");
                    var ContentId = (from elemento in DB.Contenuto where elemento.PK_Content_ID == id select elemento).First();

                    if (ContentId.PK_Content_ID==id)
                    {
                        DB.Attach(ContentId);
                        DB.DeleteObject(ContentId);
                        DB.Detach(ContentId);
                    }
                    else
                    {
                        throw new Exception("Errore nel reperimento dell'elemento");
                    }
                }
                catch (Exception e)
                {
                    return new StandardResponse() { Success = false, Message = e.Message };
                }

                try
                {
                    DB.SaveChanges();
                }
                catch (Exception e)
                {
                    throw new Exception("Errore nel salvataggio modifiche sul DB." + e.Message);
                }
            }

            return new StandardResponse() { Success = true };
        }
    }
}

【问题讨论】:

    标签: c# .net database entity-framework


    【解决方案1】:

    您缺少 DB.SaveChanges()。最好在 StackExchange.Com 上问这类问题。

    【讨论】:

      【解决方案2】:

      移除 Detach 调用。当您执行 SaveChanges 时,上下文会查看它正在跟踪的所有对象。由于您执行了 Detach,它不再跟踪该实例。

      【讨论】:

        猜你喜欢
        • 2015-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-07
        • 1970-01-01
        • 2014-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多