DbContext的ChangeTracker问题 [英] DbContext's ChangeTracker problem

查看:379
本文介绍了DbContext的ChangeTracker问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于代码优先EF-4.1的程序.用户获得上下文并可以修改某些属性.完成用户操作后,我会快速执行

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);

确定是否需要SaveChanges().如果我执行"SaveChanges()"调用,则所做的更改将保存到数据库中.

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.

这适用于某些属性,不适用于其他属性.具体来说,它似乎适用于简单类型(float s)和集合层次结构(ObservableCollection s).

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).

我做错什么了吗?

推荐答案

是的,这是一个问题. DbChangeTracker无法跟踪某些关系. 独立关联和外键关联.在以下情况下,将跟踪关系的更改:

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:

  • 一对一关系在EFv4 +中始终是外键关联
  • 与外键关联的一对多关系-您应该设置外键属性

在以下情况下,不会跟踪对关系的更改:

Changes to relation are not tracked in case of:

  • 与独立协会的一对多关系
  • 多对多关系始终是独立协会

未跟踪独立关联"是不正确的命名.跟踪了这些更改,但DbChangeTracker 不会公开访问这些更改!您必须将DbContext转换为ObjectContext,并使用ObjectStateManager来访问代表独立关联的ObjectStateEntries.

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.

在这种情况下,最简单的方法就是始终始终调用SaveChanges.如果不需要保存任何数据,它将不执行任何数据库命令.

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.

这篇关于DbContext的ChangeTracker问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆