0

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 ProductID and CategoryID)
  • The names of the respective relationships from each table to the intersection ("Categories" and "Products").

How do I do it?

Shaul Behr
  • 36,951
  • 69
  • 249
  • 387

1 Answers1

0

If I'm getting it right - you should try what we did in here (with the OP's help).
I think that comes pretty close...

How I can read EF DbContext metadata programmatically?

specifically, I think...

ManyToManyReferences = navigationProperties.Where(np =>
            np.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many &&
            np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
            .Select(np => Extensions.CreateLambdaExpression<TEntity>(np.Name))
            .ToList();  


You may also wanna check this one (and links to other posts I gathered there) for more on the metadata. Or search for IObjectContextAdapter or some of the keywords mentioned in here

Get entity facets and other metadata on runtime

Community
  • 1
  • 1
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51