What is AsNoTracking in Entity Framework
Hi guys, I am currently working on how to speed up ef core?
I found first, asnotracking feature
DbConn db = serviceProvider.GetService<DbConn>();
var Animals = db.Animals;
var Animals2 = db.Animals.AsNoTracking().ToList();
What is differences Animals vs Animals2 ?
EF is caching all entities that you have done, then when you use SaveChanges feature, it will append all changes to the DB, it seems good and makes it easy to save something, but watching every single process on DB is not good.
What should we do?
If you don't need to track changes like you just want to read data from DB, you should add asnotracking feature otherwise your changes will not append on DB
Animal newAnimal = new Animal {Name = "bobo", Species= "dog"}
Animals.Add(newAnimal);
Animals2.Add(newAnimal);
db.SaveChanges();
So what will happen? it will save changes on Animals but it will not save on Animals2
Note: Animals and Animals2 pointing the same field on DB so it will add for this example, My point is if you use asnotracking it will not append any changes on DB, you should specify before save if you want to append with asnotracking
What about Performance?
without asnotracking it completed in 460,85 ms
with asnotracking it completed in 381,71 ms
Resources
https://stackoverflow.com/questions/12211680/what-difference-does-asnotracking-make/22807021
https://docs.microsoft.com/en-us/ef/core/querying/tracking
https://www.gencayyildiz.com/blog/entity-framework-asnotracking-ile-takip-sonlandirma/