Change Tacking EF Core
One of the best features of EF is its ability to track changes done to the entities you work with. This way developers may focus their attention on business logic not managing entity states. Entity framework core keeps the state of the entity objects inside its DBContext.
How it all works
First you will need to pull an entity from the context. This is done by LINQ queries or methods like DbSet.ToList() or DbSet.FirstOrDefault() that is executed against the database you work with. All the entities returned from the query will be automatically tracked. The initial state of these entities is Unchanged.
1var context = new SupermarketContext();
2using (context)
3{
4 var store = context.Stores.Where(s => s.Name == "Store 1").FirstOrDefault();
5 var storeEntry = context.Entry<Store>(store);
6 Console.WriteLine(storeEntry.State); //Unchanged
7}
8
Another scenario is when you build an Web API and you receive a JSON object that represents your Entity object. Instead of pulling the object from the database first you may parse the json into an Entity object and attach it to the context. Here you will need the Id of the entity object so that the context knows exactly which the object is even if the object itself is not pulled from the database. When the object is attached the state of the object is again Unchanged. When SaveChanges is called no actual command will be created for this object as the state is not marked as Modified.
1var context = new SupermarketContext();
2using (context)
3{
4 var store = new Store()
5 {
6 Id = 1,
7 Name = "Store 1",
8 Location = "Location 1",
9 };
10
11 context.Attach(store);
12 var storeEntry = context.Entry<Store>(store);
13 Console.WriteLine(storeEntry.State); // Unchanged
14 context.SaveChanges();
15}
16
If you want to trigger updates on all fields you can mark the store entity as modified.
1using (context)
2 {
3 var store = new Store()
4 {
5 Id = 1,
6 Name = "Store 1",
7 Location = "Location 1 - modified",
8 };
9
10 context.Attach(store);
11 var storeEntry = context.Entry<Store>(store);
12 Console.WriteLine(storeEntry.State); // Unchanged
13
14 storeEntry.State = EntityState.Modified;
15
16 context.SaveChanges();
17 }
18

Alternatively you can Update the store entity instead of explicitly changing the state. It will result in the same update.
1var context = new SupermarketContext();
2using (context)
3{
4 var store = new Store()
5 {
6 Id = 1,
7 Name = "Store 1",
8 Location = "Location 1 - modified upadted state",
9 };
10
11 context.Update(store);
12 var storeEntry = context.Entry<Store>(store);
13 Console.WriteLine(storeEntry.State); // Modified
14
15 context.SaveChanges();
16}
17

In case you only want to update one of the properties you can attach the store object and mark only the specific property as Modified.
1var context = new SupermarketContext();
2 using (context)
3 {
4 var store = new Store()
5 {
6 Id = 1,
7 Name = "Store 1",
8 Location = "Location 1 - only prop modification",
9 };
10
11 context.Attach(store);
12 var storeEntry = context.Entry<Store>(store);
13 Console.WriteLine(storeEntry.State); // Unchanged
14 storeEntry.Property(x=>x.Location).IsModified = true;
15
16 context.SaveChanges();
17 }
18

Note that if the attached entity doesn't have an id its state is no longer Unchanged but Added.
1var context = new SupermarketContext();
2 using (context)
3 {
4 var store = new Store()
5 {
6 Name = "New Store",
7 Location = "New Location",
8 OpenHours = 24
9 };
10
11 context.Attach(store);
12 var storeEntry = context.Entry<Store>(store);
13 Console.WriteLine(storeEntry.State); // Added
14
15 context.SaveChanges();
16 }
17

Linked items without id will be with state Added too and will be inserted into the database.
1var context = new SupermarketContext();
2 using (context)
3 {
4 var inventory = new Inventory() { Name = "Soap" };
5 var store = new Store()
6 {
7 Id = 1,
8 Name = "New Store",
9 Location = "New Location",
10 OpenHours = 24,
11 Inventory = new List<Inventory>()
12 {
13 inventory
14 }
15 };
16
17 context.Attach(store);
18 var storeEntry = context.Entry<Store>(store);
19 Console.WriteLine(storeEntry.State); // Unchanged
20
21 var inventoryEntry = context.Entry<Inventory>(inventory);
22 Console.WriteLine(inventoryEntry.State); // Added
23
24 context.SaveChanges();
25 }
26

Linked items with id will be in Unchanged state.
Stop change tracking
Sometimes you may want to stop the tracking of an object and sometimes we may stop the tracking unintentionally. That is why it is a good idea to know when the change tracking stops.
Disposing the DBContext - One way to stop all tracking is by disposing of the DBContext.
Manually clearing the change tracker - Calling
dbContext.ChangeTracker.Clear()
will detach all entities and stop tracking them. This method is preferred when you want to detach all the entities versus detaching the entities one by one. Detaching all entities at once is much faster.Manually change the entity state - You can always explicitly detach a single entity by changing its state
dbContext.Entry(entity).State = EntityState.Detached
.Use non-tracking queries - For read-only data, you can use
AsNoTracking
queries. This improves the performance of the queries.1var inventories = context.Inventories.AsNoTracking().ToList();
State | Description | Action on Save Changes |
---|---|---|
Detached | Entity is not being tracked by the DbContext. | No action is taken. |
Added | Entity is new and will be inserted into the database. | INSERT operation is performed. |
Unchanged | Entity has not been modified since retrieval. | No action is taken. |
Modified | Entity has been updated since retrieval. | UPDATE operation is performed. |
Deleted | Entity is marked for deletion in the database. | DELETE operation is performed. |