I'm creating an application that has numerous business entities. I'd like to make sure that every time one is modified, I timestamp the record accordingly and place the creating/modifying user. I have a group of entities and service classes for those entities. All of the entities implement IBaseEntity and inherit BaseService.
public interface IBaseEntity
{
int Id { get; set; }
DateTime CreatedOn{ get; set; }
DateTime LastModifiedOn { get; set; }
Employee CreatedBy { get; set; }
Employee LastModifiedBy { get; set; }
}
public abstract class BaseService
{
public void Create(IBaseEntity entity)
{
entity.CreatedBy = new Employee { Id = entity.Id };
entity.CreatedOn = DateTime.UtcNow;
entity.LastModifiedBy = new Employee { Id = entity.Id };
entity.LastModifiedOn = DateTime.UtcNow;
}
}
and in my EmployeeService, I would call my base Update and Create methods prior to adding or attaching the entity.
public Employee Create(Employee employee)
{
// Create User
base.Create(employee);
context.Employees.Add(employee);
context.SaveChanges();
}
Ideally I'd like to pass the entity by reference but I know this isn't possible. My question is, how can I achieve this so that I can centralize this code and not have to implement within each of my service classes.