Question

I am using MVC3, C#, Razor, EF4.1 (MS SQL2008 (dev) and SQL Azure (Test, Live)).

I would like to add a "CreatedBy" and "UpdatedBy" columns to certain tables and use the application "principal" username as values for these columns. I am using Membership Services. I have already implemented the "CreatedOn" and "UpdatedOn" columns using triggers. I cannot do the same with "CreatedBy" and "UpdatedBy" columns as the database does not know the application usernames. Can you provide an approach/code samples to do this within the MVC application which does not require me to write update code in all places that update the entities. I may be thinking about an extension to "SaveChanges()".

I do realise that this question is related to change tracking, and EF4.1 has features built in for auditing. However this is different in that it writes all changes to an audit table which may be good, but in my case it would be helpful to have username data on the record as well. One area where this is helpful is when one is doing data comparisons between DBs and one wishes to avoid records added or updated by other folks. For pure play auditing I may well add EF4.1's change tracking feature in the future.

Thanks in advance.

EDIT:

Is there any pre Event where I could insert this code like "onSaving" or equivalent?

Was it helpful?

Solution

Use ObjectContext.SavingChanges event for this purpose. Handle entities being saved

context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)

and set your CreatedBy and UpdatedBy column values.

http://msdn.microsoft.com/en-us/library/cc716714.aspx

If you are working with DbContext, use following code to retrieve ObjectContext from it:

var adapter = (IObjectContextAdapter)dbContext;
var objectContext = adapter.ObjectContext;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top