I have two tables, Product and Category, which have a pure many to many intersection table, ProductCategory (i.e. ProductCategory contains only two fields, ProductID and CategoryID). EF has modeled this nicely for me, such that Product has a Categories property and Category has a Products property.
Now I want to create an audit trail, catching whenever a record is inserted, updated or deleted. This I have successfully achieved by creating the other half of the partial class MyEntities and overriding SaveChanges(). Thus:
public override int SaveChanges(SaveOptions options)
{
var inserts = ObjectStateManager.GetObjectStateEntries(EntityState.Added).ToList();
var updates = ObjectStateManager.GetObjectStateEntries(EntityState.Modified).ToList();
var deletes = ObjectStateManager.GetObjectStateEntries(EntityState.Deleted).ToList();
...
}
and for each ObjectStateEntry in each of inserts, updates and deletes I can get the entity being modified through the Entity property.
This works great for regular tables like Product and Category, but it bombs out with ProductCategory, because the Entity property is null. I've dug around at runtime through the public interface of the ObjectStateEntry for the inserted/deleted ProductCategory, but can't find anything that will help me identify the key fields and their values. I want to get:
- The names of the related tables ("Product" and "Category")
- The key values of the related records (values of
ProductIDandCategoryID) - The names of the respective relationships from each table to the intersection ("Categories" and "Products").
How do I do it?