5

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.

4

1 に答える 1

6

DbContextChangeTrackerすべての情報を保持していないため、変更を追跡していません。エンティティの状態のみを提供できますが、独立した関連付けの状態 (つまり、多対多および一部の 1 対多の関係の状態) は提供できません。多対多の関係の状態を取得したい場合は、@Mark Oreta が提供するリンクで説明されているように取得ObjectContextして質問する必要があります。ObjectStateManager

于 2012-10-03T08:54:15.280 に答える