Tuesday, November 4, 2014

Change tracking behavior of Entity Framework

Change tracking is one great feature of Entity Framework, which automatically detects the change in Entity. It is cool and no extra effort needed to enable this behavior but sometimes this feature may degrade performances.

Because Entity Framework uses resource to keep track on entity this is one disadvantage. Sometime it’s not even needed to keep track on change. There might be situation that just we want to read the data and we do not want to save it, in this situation, tracking on change is useless.
In this example, we will see how entity framework track changes and how we can disable it programmatically.  

using(var db = new AppEntities())
                {
                     var data = db.Books.Where(f => f.id == 1).FirstOrDefault();

                    Console.WriteLine("Before Change : " + db.Entry(data).State);

                    data.name = "Changed";

                    Console.WriteLine("After Changed: " + db.Entry(data).State);

                }


In this code ,we are reading the entity at first and printing the state of entity then we are modifying some property and again printing the current state.


Now we are seeing that Entity Framework is tracking changes of entity. Here we will learn to disable the feature. Have a look in below code.


The highlighted line will disable change tracking of entity. Here is output


Now, we are seeing the status is always “Unchanged”. So, Entity Framework is no more tracking the change. 

No comments:

Post a Comment