0

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.

XVargas
  • 1,512
  • 2
  • 13
  • 16
  • 1
    Any class instance is a reference in C#. Please, explain more. – Igor Mar 19 '13 at 04:50
  • Why do you say you can't pass it by reference? As your code stands currenty there would be no problem passing your employee class to your Create method. – shenku Mar 19 '13 at 04:54
  • Sorry, I should clarify. As it stands now, my implementation of this solution does not work. The values edited in the base class aren't affecting the employee entity as I assumed it would. My next thought was to pass it by reference before attaching. Yes, I can pass it but if I try to pass it by reference, Create(ref employee), the compiler complains that I cannot pass an Employee as it's expecting an IBaseEntity. – XVargas Mar 19 '13 at 04:59
  • 1
    Inspect `employee` instance before and after `base.Create(employee);` - it should be affected by the four property assignments there if `public Employee Create(Employee employee)` is in the class descending from `BaseService`. – Igor Mar 19 '13 at 05:06

1 Answers1

1

Igor was right! I was getting, "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value." and had assumed that the values were not being set. It was actually due to a completely different issue. Thanks for pointing me in the right direction.

XVargas
  • 1,512
  • 2
  • 13
  • 16