许多关系检测变化 [英] Many to many relationship detecting changes

查看:89
本文介绍了许多关系检测变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解为什么DbContext不会检测到多对多关系的变化。这是我在模型配置中设置的:

  this.Configuration.ValidateOnSaveEnabled = false; 
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.LazyLoadingEnabled = false;

这是测试代码:

  var book = Context.Set< Book>()。其中​​(b => b.Id == 1).Single(); 
var author = Context.Set< Author>()。其中​​(a => a.Id == 2).Single();

book.Authors.Add(author);

如果我检查更改,它不报告任何:

  //返回false 
_context.ChangeTracker.Entries()。(e => e.State == EntityState.Added || e。 State == EntityState.Modified || e.State == EntityState.Deleted);

如果我保存更改,更改将正确更新到数据库。

  //添加到BookAuthors表的1条记录
_context.SaveChanges();

为什么DbContext无法跟踪多对多的更改? WCF不涉及,这是直接连接到Sql server。

解决方案

DbContext 不跟踪更改,因为 ChangeTracker 不包含所有信息。它只能给你唯一的实体状态,而不是独立协会的状态(这是多对多和一对一关系的状态)。如果要获得多对多关系的状态,您必须获得 ObjectContext 并询问 ObjectStateManager ,如链接由@Mark Oreta提供。


I am trying to understand why DbContext doesn't detect changesin many-to-many relationship. This is what I have set in model configuration:

this.Configuration.ValidateOnSaveEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.LazyLoadingEnabled = false;

This is the test code:

var book = Context.Set<Book>().Where(b => b.Id == 1).Single();
var author = Context.Set<Author>().Where(a => a.Id == 2).Single();

book.Authors.Add(author);

if I check for changes, it doesn't report any:

// returns false
_context.ChangeTracker.Entries().Any(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted);

If I save changes, changes are updated to database correctly.

// 1 record added to BookAuthors table
_context.SaveChanges();

Why is DbContext not tracking changes for many-to-many? WCF is not involved, this is a direct connection to Sql server.

解决方案

DbContext is not tracking changes because ChangeTracker doesn't hold all information. It is able to give you only state of entities but not state of independent associations (that is state of many-to-many and some one-to-many relations). If you want to get state of many-to-many relation you must get ObjectContext and ask ObjectStateManager as described in the link provided by @Mark Oreta.

这篇关于许多关系检测变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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