1

I have some tables:
- Account (Id, Code, Name, Email, Address, Phone, CreatedDate, CreatedBy, ModifiedDate, ModifiedBy)
- Product (Id, Code, Name, Price, CreatedDate, CreatedBy, ModifiedDate, ModifiedBy)
- OrderDetail (OrderId, ProductId, Amount, Price, CreatedDate, CreatedBy, ModifiedDate, ModifiedBy)
- Param (Code, Name, Value)

And I have class/interface: - AuditableEntity (CreadtedDate, CreatedBy, ModifiedDate, ModifiedBy) - BaseEntity/CodeEntity/CommonEntity (Code)

Account, Product, OrderDetail need AuditableEntity Param needs BaseEntity

If Param needs AuditableEntity in the future, easy to attach Audit to Param.
When user add and commit entity to database, fields CreatedDate and CreatedBy are automatically added. The same thing with UpdatedDate and UpdatedBy in update/edit case.
I have implemented add or update case by create AuditableEntity and modified tt file in EF to force all entities inherit to it (but not the good practice cause some tables don't need auditing).

I think that be can use interface instead of class and let entity is partial type. But I'm not sure about that so I need your advise or if you have better design, I'm very appreciated with your help.

1 Answer 1

1

I like to use interfaces and do the work in the DbContext.

public interface ITrackedEntity : IEntity
{
    string CreatedUserId { get; set; }
    DateTime CreatedDate { get; set; }
    string LastUpdateUserId { get; set; }
    DateTime LastUpdateDate { get; set; }
}

And then in my overridden SaveChanges() method in my DbContext:

foreach (var entry in ChangeTracker.Entries<ITrackedEntity>())
{
    if (entry.State == EntityState.Added)
    {
        entry.Entity.CreatedDate = DateTime.Now;
        entry.Entity.CreatedUserId = HttpContext.Current == null ? "" : HttpContext.Current.User.Identity.Name;
        entry.Entity.LastUpdateDate = DateTime.Now;
        entry.Entity.LastUpdateUserId = HttpContext.Current == null ? "" : HttpContext.Current.User.Identity.Name;
    }
    if (entry.State == EntityState.Modified)
    {
        entry.Entity.LastUpdateDate = DateTime.Now;
        entry.Entity.LastUpdateUserId = HttpContext.Current == null ? "" : HttpContext.Current.User.Identity.Name;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi JC, how about your IEntity?
You can just exclude it from the code I posted. It isn't necessary for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.