Question

I have a codefirst EF-4.1 based program. The user gets a context and can modify some properties. When the user is done, I do a quick

ChangeTracker.Entries().Any(e => e.State != EntityState.Unchanged);

to determine if a SaveChanges() is required or not. If I do a 'SaveChanges()' call, the changes that have made are persisted to the database.

This works for some properties, and doesn't work for others. Specifically it seems to work with simple types (floats), and with collection hierarchies(ObservableCollections).

Am I doing something wrong?

Was it helpful?

Solution

Yes this is a problem. Some relations are not tracked by DbChangeTracker. There is difference between Independent association and Foreign key association. Changes to relation are tracked in case of:

  • One-to-one relation which is always Foreign key association in EFv4+
  • One-to-many relation with Foreign key association - you should set up foreign key property

Changes to relation are not tracked in case of:

  • One-to-many relation with Independent association
  • Many-to-many relation which is always Independent association

Not tracked for Independent association is not correct naming. These changes are tracked but DbChangeTracker does not expose access to these changes! You must convert DbContext to ObjectContext and use ObjectStateManager to get access to ObjectStateEntries representing independent associations.

In this case the easiest thing is simply call SaveChanges always. It will not execute any DB commands if no data need to be saved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top