Reputation: 1
I want to save all of the CRUD operations with the user's detail to the database and then monitor these info according to the following approach below. In my opinion, the second approach seems better so that it can be managed from one specific table and can also be used for the critical info. So, could you please clarify me by giving an applicable example on how to perform this best in both cases with a framework or a custom code that is suitable for MVC5 and MsSQL Server? Thanks in advance.
Approach I: By adding "CreatedBy", "CreatedOn", etc. columns to the related tables and add/update the info ("CreatedBy", "CreatedOn", etc.) on these tables whenever a records is added or updated. In that case only the last update info will be obtained from the database and the prior operations cannot be obtained.
Approach II: By creating a new table in the database and add a new record for every CRUD operation containing "CreatedBy", "CreatedOn", "Controller", "Action", "Record Id", "Upadte Value", and the other necessary fields.
Upvotes: 0
Views: 4025
Reputation: 1
Finally I found Bilal Fazlani's perfect article "Adding Log Feature to Entity Framework" and that is really very easy to integrate to the project. Anyone who need to log/audit in Entity Framework by using Code First approach easily apply it to their own project. Thanks a lot for your help...
Upvotes: 0
Reputation: 866
We use Approach 1 in all of our solutions:
public partial class Database
{
public Database(DbConnection connection)
: base(connection, true)
{
CurrentUser = "SYSTEM";
}
public string CurrentUser
{
get;
set;
}
public override int SaveChanges()
{
var changeSet = ChangeTracker.Entries();
if (changeSet != null)
{
foreach (var change in changeSet.Where(x => x.State != EntityState.Unchanged))
{
if (change.State == EntityState.Added)
{
SetCreatedFields(change);
SetLastChangedFields(change);
}
if (change.State == EntityState.Modified)
{
SetLastChangedFields(change);
}
}
}
return base.SaveChanges();
}
private void SetLastChangedFields(DbEntityEntry change)
{
var entity = change.Entity as dynamic;
entity.LastChangedBy= !string.IsNullOrEmpty(CurrentUser) ? CurrentUser : "System";
entity.LastChanged = DateTime.Now;
}
private void SetCreatedFields(DbEntityEntry change)
{
var entity = change.Entity as dynamic;
entity.CreatedBy = !string.IsNullOrEmpty(CurrentUser) ? CurrentUser : "System";
entity.Created = DateTime.Now;
}
}
I realize it's not very good practice to use dymanic
but it's simple and it works.
Upvotes: 2