Many to many relationship detecting changes

荒凉一梦 提交于 2020-01-14 09:23:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/12699892/many-to-many-relationship-detecting-changes

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