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?
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 .
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.