DbContext's ChangeTracker problem

时光总嘲笑我的痴心妄想 提交于 2019-12-22 01:37:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5809620/dbcontexts-changetracker-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!