I'm tring to receive an entity and then update it, but I want to get it with no tracking, so I can attach it back to the context.
I have the EntityFramework.dll
referenced (4.1). I generated the database from the model. (not code-first).
Get user:
db.Users.MergeOption = MergeOption.NoTracking; IQueryable<User> query = db.Users;//.AsNoTracking(); //<-- apparently, this is code-first only. return query;
Update user:
db.Users.Attach(user); //error here. ObjectStateEntry entry = db.ObjectStateManager.GetObjectStateEntry(user); entry.SetModifiedProperty(propertyName); db.SaveChanges(); return user;
Error:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I call the method like this:
var user = userRepository.GetUsers().FirstOrDefault(u => u.UserId == userId); user.Identifiers.Add(someIdent); userRepository.UpdateUser(user);
In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.
The AsNoTracking() extension method returns a new query and returned entities do not track by the context. It means that EF does not perform any additional task to store the retrieve entities for tracking. We can also change the default behavior of tracking at context instance level.
AsNoTracking() . This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query.
Tracking behavior controls if Entity Framework Core will keep information about an entity instance in its change tracker. If an entity is tracked, any changes detected in the entity will be persisted to the database during SaveChanges() .
No-tracking Queries Sometimes you may want to query for entities but not have the entities be tracked by the context. This may result in better performance when querying for large numbers of entities in read-only scenarios. The AsNoTracking extension method executes a query and returns the results without tracking them in the context. In the following example, the queries will return objects but they will not be tracked by the context. other
// Query for all departments without tracking them var departments1 = context.Departments.AsNoTracking().ToList(); // Query for some departments without tracking them var departments2 = context.Departments .Where(d => d.Name.StartsWith("math")) .AsNoTracking() .ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With