简体   繁体   中英

Delete Db element with EntityFrameWork

I'm trying to implement a method that deletes an element of a DB table.

The following code doesn't throw any exceptions, but the element still exists inside the table after it executes.

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

You're missing DB.SaveChanges(). It's probably best to ask this type of question on StackExchange.Com.

Remove the Detach call. When you do SaveChanges, the context looks at all the objects that it's tracking. Since you did a Detach, it isn't tracking that instance anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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