I would like to create a repository based on the entity type. Any ideas how to do that?
- We have a lot of entities, so this needs to be generic code.
- We need to have history tables for every entity that we have.
- We are using code-first,
DbContext, EF 5.0 using repository and unit of work patterns.
Below is the code we have to get changes in the SaveChanges method. For every modified and deleted entity we would like to save the old row into a history table. Below is hard coded for a single entity: ServiceLocation.
All entities have a corresponding history entity. For example, for the ServiceLocation entity there is a ServiceLocationHistory entity (and repository).
If the modifiedEntity is of type ServiceLocation, how do I create a ServiceLocationHistoryRepository? And make it generic for all types?
public override int SaveChanges()
{
// Get the entities that changed
var addedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added && e.Entity is IHistoryBase).Select(e => (TBaseEntity)e.Entity);
var modifiedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified && e.Entity is IHistoryBase).Select(e => (TBaseEntity)e.Entity);
var deletedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted && e.Entity is IHistoryBase).Select(e => (TBaseEntity)e.Entity);
// Debugging watch varibles
int x = addedEntries.Count();
int y = modifiedEntries.Count();
int z = deletedEntries.Count();
// Create the Type adapter
TypeAdapter adapter = new TypeAdapter(new RegisterTypesMap[] { new HistoryRegisterTypesMap() });
var serviceLocationHistoryRepository = new ServiceLocationHistoryRepository(this);
foreach (var addedEntry in addedEntries)
{
addedEntry.FromDate = DateTime.Now;
addedEntry.ToDate = DateTime.Parse("9999-12-31 00:00:00.0000000");
}
foreach (var modifiedEntry in modifiedEntries)
{
ServiceLocationHistory history = adapter.Adapt<ServiceLocation, ServiceLocationHistory>(modifiedEntry as ServiceLocation);
serviceLocationHistoryRepository.Add(history);
history.FromDate = modifiedEntry.FromDate;
history.ToDate = modifiedEntry.FromDate = DateTime.Now;
modifiedEntry.ToDate = DateTime.Parse("9999-12-31 00:00:00.0000000");
}
foreach (var deletedEntry in deletedEntries)
{
ServiceLocationHistory history = adapter.Adapt<ServiceLocation, ServiceLocationHistory>(deletedEntry as ServiceLocation);
serviceLocationHistoryRepository.Add(history);
history.FromDate = deletedEntry.FromDate;
history.ToDate = DateTime.Now;
}
return base.SaveChanges();
}
Below is the proof of concept code I used to get the repository based on the type.