hello B
hello B

Reputation: 963

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

Upvotes: 0

Views: 129

Answers (2)

James Manning
James Manning

Reputation: 13579

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.

Upvotes: 0

tzerb
tzerb

Reputation: 1433

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

Upvotes: 3

Related Questions