In this post we will be discussing about Tracking vs No-Tracking in Entity Framework. Tracking the entities in the context is useful when you want to change anything in that entity. But Sometimes you only want to query the entities and wants it to be queried fast. Thus No-Tracking comes into picture which will ensure minimal memory usage and optimal performance.
What is No-Tracking Queries
No-Tracking queries allows you to tell Entity Framework not to track the results of a query. That means Entity Framework performs no additional processing or storage of the entities which are returned by the query. Thus it also means that you cannot update these entities without reattaching them to the tracking graph.
How to use No-Tracking
Using No-Tracking is relatively simple and easy. Add using System.Data.Entity if its not added already and then include .AsNoTracking() on your query as shown below
var user = dbContext.Users.AsNoTracking() .Where(user => user.UserId == userid) .SingleOrDefault(); return user;
When we use function AsNoTracking() on the query we are explicitly telling Entity Framework that the entities are not tracked by the context. If you want to make changes to un-tracked entities you must remember to attach them before calling SaveChanges.
context.Attach(Users); context.SaveChanges();
Does Anonymous Type are Tracked ?
If the anonymous type has the instance of entity types they will be tracked by default. That means the below anonymous types are tracked
var user = dbcontext.Users.Select(u = > new { User = u, Employee = u.Employee });
But if the result set does not contain any entity type, no tracking is performs as shown below :
var user = dbcontext.Users.Select(u = > new { UserID = u.UserId, FirstName = u.FirstName, LastName = u.LastName });
Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.
Related articles
- Convert any Websites to a desktop Application using Nativefier
- Containerized Unit Testing Nodejs Applications with Dockunit
- How to exit in Node.js
- How to solve nodejs Error: listen EADDRINUSE
- [Solved] Typescript Compilation Error TS5037 : Cannot compile external modules
- Run multiple versions of Node.js in a System
- Change the User Level Configuration when installing Nodejs Packages
- Getting Started with Node.js
- How to build Visual Studio project using MSBuild in Jenkins
- 10 Interview Questions on Nodejs
nice article. poor choice of font
ReplyDelete