我想根据实体类型创建一个存储库。任何想法如何做到这一点?
- 我们有很多实体,所以这需要是通用代码。
- 我们需要为我们拥有的每个实体提供历史记录表。
- 我们使用代码优先,
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();
}