views:

24

answers:

1

Hi, i have the following db structure:

Users:
- UserID
- UserName
- FirstName
- LastName
...

UsersLog:
- UserLogID
- UserID
- UserName
- FirstName
- LastName
...
- DateCreated

The log table simply inserts a record against the user everytime an insert or edit is made. The reason i have the log table is that when an order is submitted i can simply log the user log id against the order which means i have a representation of the user data at the time of the order. I was wondering what is the best way to map this? Currently i have both tables mapped which allows me to say:

var user = new User { ... };
userRepository.Insert(user);

userLogRepository.Insert(new UserLog { User = user, UserName = user.UserName, FirstName = user.FirstName, ..., DateCreated = DateTime.UtcNow });

My biggest problem so far is that i have to re-add every field when inserting into the log table. I know i can create a constructor to handle this but i was wondering if there was a better way of handling this. I'd appreciate it if someone could help.

Thanks

+2  A: 

If you're just concerned about the mapping code, you could use Automapper

Your code would look something like (this is off the top of my head, but I think it's about right):

// Call on app startup, don't try to set the UserLogId field
Mapper.CreateMap<User, UserLog>()
   .ForMember(log => log.UserLogId, opt => opt.Ignore());;

// call when saving the user
userLogRepository.Insert(Mapper.Map<User, UserLog>());

Alternatively, if you don't like where the code is sitting, you could look at using an Audit Event Listener

David