Clarification on behaviour of QueryTrackingBehavior property of ChangeTracker (EF Core) - entity-framework-core

Please help with clarification on behaviour of EF Core when QueryTrackingBehavior property of ChangeTracker is changed.
Let say up to this point in the code, we have everything at default (which means all queries are tracked). Some data has been read/updated and tracked.
Now we update QueryTrackingBehavior property of ChangeTracker to NoTracking. Does this "reset" the tracking of the entities that were read previously?
Let's say we read additional data (not tracked now).
If we change QueryTrackingBehavior property of ChangeTracker back to TrackAll, do the entities read prior of the change retain their tracking so that SaveChanges() performs the right updates, ignoring anything that was read while the ChangeTracker was set to NoTracking?

Setting QueryTrackingBehavior only affects queries that run subsequently and modifying this property doesn't affect the states of tracked entities.
This can be checked by listing the entities in the change tracker, for example:
context.Products.Find(1);
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
context.Products.Find(2);
context.Products.Add(new Product { Id = 21 });
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.TrackAll;
context.Products.Find(3);
var ids = context.ChangeTracker.Entries()
.Select(e => ((Product)e.Entity).Id).ToList();
The result is:
21
1
3
As you see, Product 2 isn't tracked, while entities can still be attached to the change tracker when QueryTrackingBehavior is set to NoTracking, hence the name "query tracking behavior".

Related

One to many relation : child is flagged Modified instead Deleted

I have some troubles using One to Many relationships with EntityFramework Core. When I delete a child object in the List property on the parent, this Child object is flagged as Modified by the ChangeTracker (and not Deleted). However, when I call SaveChanges on the context, this entity is well Deleted.
Of course, I could force the flag of the entity to Deleted but, I would prefer another solution because I'm using AutoMapper to update my entities. and I don't want to mix the AutoMapper mapping process and EntityFramework Context.
var parent = new Parent();
var child = new Child();
parent.Childs.Add(child);
await context.SaveChangesAsync();
// removing the first child
parent.Childs.RemoveAt(0);
// fails (Expected Deleted, got Modified)
Assert.Equal(EntityState.Deleted, context.Entry(child).State);
The best explanation of this behavior is contained inside one of the expected breaking changes in EF Core 3.0 - Cascade deletions now happen immediately by default:
Old behavior
Before 3.0, EF Core applied cascading actions (deleting dependent entities when a required principal is deleted or when the relationship to a required principal is severed) did not happen until SaveChanges was called.
New behavior
Starting with 3.0, EF Core applies cascading actions as soon as the triggering condition is detected. For example, calling context.Remove() to delete a principal entity will result in all tracked related required dependents also being set to Deleted immediately.
Why
This change was made to improve the experience for data binding and auditing scenarios where it is important to understand which entities will be deleted before SaveChanges is called.
The first section explains the current behavior and the last section explains why they are changing it - to help usage scenarios like yours.
With that being said, you should either apply the cascade option manually, or wait for EF Core 3.0 if you can afford that.

Do I have to set foreign key properties manually when I change associations?

I'm migrating from Linq-to-SQL to Entity Framework (4.4), using Database First with a DbContext. I'm wondering whether the following behavior is normal:
using (var e = new AgendaEntities()) {
var store = e.Stores.First();
var office = e.Offices.Create();
office.Store = store; // Set association
Console.WriteLine(office.StoreID); // shows Guid.Empty, expected store.ID!
}
In L2S, setting the Store association to an entity would also update the StoreID key. In EF, this doesn't seem to be happening. This is regardless of whether the entities are new or loaded from the context.
When I SaveChanges, it saves correctly and the StoreID is updated to match office.ID, but why does this only happen after the save?
Is there something I'm missing, or am I now supposed to keep foreign keys in sync manually?
Solution Edit:
This is called property fixup, and used to be done automatically by the generated proxies. However, with DbContext this is no longer the case. According to this Connect issue, this is by design.
Hello,
The DbContext template actually doesn't generate classes that will be used as change tracking proxies - just lazy loading proxies (which don't do fix-up). We made this decision because change tracking proxies are complex and have a lot of nuances that can be very confusing to developers.
If you want fix-up to occur before SaveChanges you can call myContext.ChangeTracker.DetectChanges.
~EF Team
An alternative is to call DbContext.Entry(entity), which will sync up the entity. This is described in this article: Relationships and Navigation Properties under "Synchronizing the changes between the FKs and Navigation properties"
No. Entity framework does this for you. Read Relationships and Navigation Properties for more information.
By assigning a new object to a navigation property. The following
code creates a relationship between a course and a department.
If the objects are attached to the context, the course is also
added to the department.Courses collection, and the
corresponding foreign key property on the course object is set to the
key property value of the department.
course.Department = department;
But as you observed, this only happens after you call SaveChanges or one of the other actions mentioned in the "Synchronizing the changes between the FKs and Navigation properties" portion of the document linked above.
If you are using POCO entities without proxies, you must make sure
that the DetectChanges method is called to synchronize the related
objects in the context. Note, that the following APIs automatically
trigger a DetectChanges call.
DbSet.Add
DbSet.Find
DbSet.Remove
DbSet.Local
DbContext.SaveChanges
DbSet.Attach
DbContext.GetValidationErrors
DbContext.Entry
DbChangeTracker.Entries
Executing a LINQ query against a DbSet
If this is not happening at all, my guess is that you haven't properly defined StoreID as the foreign key of the navigation property Store.

EF Code First - How does it know which objects to update?

As in the title, I have a method:
void method(MyDb db, Thread thread, Post post)
{
thread.Title = "changed";
db.SaveChanges();
}
(of course thread item is within MyDb object)
How does it recognize items that need to be updated? I didn't specify anywhere anything like db.Update(thread) or anything like that, it knew what to update without my help. What mechanisms are under it?
When you load entity Thread from database it becomes by default "attached". It means EF internally keep reference to your entity and it also keeps original values of the entity when you loaded it from the database.
When you updated a title there may be two scenarios:
You are using change tracking proxies and EF was notified about your change so it now knows that your instance was modified and it applies those changes to database when you call SaveChanges
You are not using change tracking proxies and when you call SaveChanges EF goes through its internally maintained list of entity references and check if any entity has any property different from original values - all such entities and their modified properties are updated to database during SaveChanges
You can read more about that process here.

Is it possible to tell if an entity is tracked?

I'm using Entity Framework 4.1. I've implemented a base repository using lots of the examples online. My repository get methods take a bool parameter to decide whether to track the entities. Sometimes, I want to load an entity and track it, other times, for some entities, I simply want to read them and display them (i.e. in a graph). In this situation there is never a need to edit, so I don't want the overhead of tracking them. Also, graph entities are sent to a silverlight client, so the entities are disconnected from the context. Hence my Get methods can return a list of entities that are either tracked or not. This is achieved dynamically creating the query as follows:
DbQuery<E> query = Context.Set<E>();
// Track the entities in the context?
if (!trackEntities)
{
query = query.AsNoTracking();
}
However, I now want to enable the user to interact with the graph and edit it. This will not happen very often, so I still want to get some entities without tracking them but to have the ability to save them. To do this I simply attach them to the context and set the state as modified. Everything is working so far.
I am auditing any changes by overriding the SaveChanges method. As explained above I may, in some low cases, need to save modified entities that were disconnected. So to audit, I have to retrieve the current values from the database and then compare to work out what was changed while disconnected. If the entity has been tracked, there is no need to get the old values, as I've got access to them via the state manager. I'm not using self tracking entities, as this is overkill for my requirements.
QUESTION: In my auditing method I simply want to know if the modified entity is tracked or not, i.e. do I need to go to the db and get the original values?
Cheers
DbContext.ChangeTracker.Entries (http://msdn.microsoft.com/en-us/library/gg679172(v=vs.103).aspx) returns DbEntityEntry objects for all tracked entities. DbEntityEntry has Entity property that you could use to find out whether the entity is tracked. Something like
var isTracked = ctx.ChangeTracker.Entries().Any(e => Object.ReferenceEquals(e.Entity, myEntity));

Entity Framework - Why explicitly set entity state to modified?

The official documentation says to modify an entity I retrieve a DbEntityEntry object and either work with the property functions or I set its state to modified. It uses the following example
Department dpt = context.Departments.FirstOrDefault();
DbEntityEntry entry = context.Entry(dpt);
entry.State = EntityState.Modified;
I don't understand the purpose of the 2nd and 3rd statement. If I ask the framework for an entity like the 1st statement does and then modify the POCO as in
dpt.Name = "Blah"
If I then ask EF to SaveChanges(), the entity has a status of MODIFIED (I'm guessing via snapshot tracking, this isn't a proxy) and the changes are persisted without the need to manually set the state. Am I missing something here?
In your scenario you indeed don't have to set the state. It is purpose of change tracking to find that you have changed a value on attached entity and put it to modified state. Setting state manually is important in case of detached entities (entities loaded without change tracking or created outside of the current context).
As said, in a scenario with disconnected entities it can be useful to set an entity's state to Modified. It saves a roundtrip to the database if you just attach the disconnected entity, as opposed to fetching the entity from the database and modifying and saving it.
But there can be very good reasons not to set the state to Modified (and I'm sure Ladislav was aware of this, but still I'd like to point them out here).
All fields in the record will be updated, not only the changes. There are many systems in which updates are audited. Updating all fields will either cause large amounts of clutter or require the auditing mechanism to filter out false changes.
Optimistic concurrency. Since all fields are updated, this may cause more conflicts than necessary. If two users update the same records concurrently but not the same fields, there need not be a conflict. But if they always update all fields, the last user will always try to write stale data. This will at best cause an optimistic concurrency exception or in the worst case data loss.
Useless updates. The entity is marked as modified, no matter what. Unchanged entities will also fire an update. This may easily occur if edit windows can be opened to see details and closed by OK.
So it's a fine balance. Reduce roundtrips or reduce redundancy.
Anyway, an alternative to setting the state to Modified is (using DbContext API):
void UpdateDepartment(Department department)
{
var dpt = context.Departments.Find(department.Id);
context.Entry(dpt).CurrentValues.SetValues(department);
context.SaveChanges();
}
CurrentValues.SetValues marks individual properties as Modified.
Or attach a disconnected entity and mark individual properties as Modified manually:
context.Entry(dpt).State = System.Data.Entity.EntityState.Unchanged;
context.Entry(dpt).Property(d => d.Name).IsModified = true;