我想基于实体类型创建一个存储库。任何想法如何做到这一点?
DbContext
,EF 5.0使用存储库和工作单元格式。以下是我们必须在SaveChanges
方法中进行更改的代码。对于每个已修改和已删除的实体,我们希望将旧行保存到历史记录表中。以下是单个实体的硬编码:ServiceLocation
。
所有实体都有相应的历史实体。例如,对于ServiceLocation
实体,有一个ServiceLocationHistory
实体(和存储库)。
如果modifiedEntity的类型为ServiceLocation
,我该如何创建ServiceLocationHistoryRepository
?并使其适用于所有类型?
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();
}