簡體   English   中英

使用EntityFrameWork刪除Db元素

[英]Delete Db element with EntityFrameWork

我正在嘗試實現一種刪除數據庫表元素的方法。

以下代碼不會引發任何異常,但是該元素在執行后仍然存在於表中。

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

您缺少DB.SaveChanges()。 最好在StackExchange.Com上問這類問題。

刪除分離呼叫。 當您執行SaveChanges時,上下文將查看其跟蹤的所有對象。 由於您進行了分離,因此不再跟蹤該實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM