Changes in many ways

I am trying to understand why DbContext does not detect many-to-many relationships. This is what I installed in the 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 does not report:

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

If I save the changes, the changes will be correctly updated to the database.

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

Why doesn't DbContext track many-to-many changes? WCF is not involved, it is a direct connection to the Sql server.

+4
source share
1 answer

DbContext does not track changes because ChangeTracker does not contain all the information. He can give you only the state of entities, but not the state of independent associations (that is, the state of many-to-many and one-to-many relationships). If you want to get a many-to-many relationship, you should get an ObjectContext and ask for an ObjectStateManager , as described in the link provided by @Mark Oreta.

+4
source

Source: https://habr.com/ru/post/1437491/


All Articles