views:

104

answers:

2

Is there a way to extract common columns from various tables into a single base class in the ADO.NET Entity Framework when using the EDMX designer? For instance, every single table in my database has a "LastUpdatedBy" and "LastUpdatedDate" column that is necessary for auditing purposes. I would like to set these values automatically in the "SavingChanges" event in my generated ObjectContext without casting to the individual entity types. See an example of this How to: Execute Business Logic When Saving Changes (Entity Framework). You can see in the example how they cast to the entity to access the various properties. I'd like to be able to case to the base type just once (if it's of that type) and set the properties.

A: 

I'm afraid probably not - as far as I understand it, the EDMX designer will generate a single (albeit partial) class for each table/entity, and you can't really "inject" any common base tables into the mix.

What you could investigate is possibly putting your common data into an interface (ICommonData) and then have the classes implement that interface.

Not sure how you'd inject that interface into the EDMX designer's process, though :-(

Marc

marc_s
A: 

Have a look at this article. It's for LINQ to SQL, but can easily be adapted to EF along the lines of this article. The first deals with your scenario, where all tables have the required audit columns, and the second looks at using a single audit table for the whole DB, and actually keeps old and new values for each change.

I am stuck between the two, because the second approach provides no means to identify newly added records, but the first has no change history. It makes me uncomfortable to have to implement two audit strategies in one application, and I need a CreatedOn value, so I'll have to use at least the first approach.

BTW, if you, like me, find XML serialization a clumsy way to store a history of object state, you could look at this EF specific solution that uses an AuditValues detail table to store old and new values of changed properties, but this one doesn't audit inserts at all.

ProfK