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.
A many-to-many relationship occurs when multiple records in a table are associated with multiple records in another table. For example, a many-to-many relationship exists between customers and products: customers can purchase various products, and products can be purchased by many customers.
The problem with many-to-many relationships is that it can cause duplications in the returned datasets, which can result in incorrect results and might consume excessive computing resources. This section provides solutions and workarounds to common scenarios with many-to-many relationships.
A many-to-many relationship exists when one or more items in one table can have a relationship to one or more items in another table. For example: Your Order table contains orders placed by multiple customers (who are listed in the Customers table), and a customer may place more than one order.
When you have a many-to-many relationship between dimension-type tables, we provide the following guidance: Add each many-to-many related entity as a model table, ensuring it has a unique identifier (ID) column. Add a bridging table to store associated entities. Create one-to-many relationships between the three tables.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With