0

Using code-first, I had doubts over what would happen if I obtained an object by querying the database, but kept using it after having it deleted or removed from the database.

For example, I performed this test:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication12
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TestDB db = new TestDB())
            {
                Usuario myUser = db.Users.FirstOrDefault();

                if (myUser != null)
                {
                    Console.WriteLine(myUser.Name);
                    db.Users.Remove(myUser);
                    db.SaveChanges();
                    Console.WriteLine(myUser.Name);
                }
            }
        }
    }
}

The test worked and the same myUser.Name was printed to the console twice. With myUser by default being a tracked object, I expected the program to crash. However it seems that the objects with all its values persisted after it was removed. Did myUser essentially become a local object and stop being tracked by the context? Would it cause any problems should I return this deleted entity through a function and store it simply as a class attribute?

5
  • deleting the record from the database does not remove the object from memory. Commented Dec 2, 2015 at 15:08
  • myUser is a local object and is unaware that it is being tracked. That responsibility lies higher up the chain. Commented Dec 2, 2015 at 15:12
  • Its worth knowing that when you retrieve an object from the database you are not working directly on the database but with the object in memory that was read from the database. Commented Dec 2, 2015 at 15:15
  • @spender so could i use the analogy that the database is a supervisor and myUser is a worker that just got fired, but retains his skillsets (a.k.a attributes)? :) Commented Dec 2, 2015 at 15:28
  • @Alex I'd suggest something more along the lines of taking an egg out of the carton, then throwing the carton away. You are still holding the egg. Commented Dec 2, 2015 at 15:37

1 Answer 1

1

The object is still in memory, but what ypu have to know is its relation with the DbContext:

What you have to examine is the object state:

DbEntityEntry entry = context.Entry(myUser);
Console.WriteLine("myUser state: " + entry.State);

Run this code before removing, afetr removing, after saving changes... That's the entity lifecycle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.