以不同的方式询问相同的问题!
似乎很明显,我需要详细说明这个问题,因为我没有可行的答案。
基于此AutoMapper注册代码:
Mapper.Initialize(cfg =>
{
cfg.AddCollectionMappers();
cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();
});
AutoMapper使用此行添加了对“更新” DbSet集合的支持:
Mapper.Map<List<DTO>, List<Entity>>(dtoCollection, entityCollection);
通过打开的上下文保存更改应该会导致更新数据库:
using (var context = factory.CreateContext())
{
Mapper.Map<List<DTO>, List<Entity>>(dtoCollection, await
context.dbSet.TolistAsync());
await context.SaveChangesAsync();
}
这什么都不做!
回到我最初的问题。如果使用dto和实体集合的当前状态调用映射器,则根据在此处创建的比较映射返回更新的实体集合:
cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<DbContext>>();
在此处产生实体集合:
var entities = Mapper.Map<List<DTO>, List<Entity>>(dtoCollection, await
context.dbSet.TolistAsync());
我是否支持迭代新集合并使用此新集合手动更新EF?目前尚不清楚我应该做什么?这是我应该对结果集合进行的处理吗?
// map dto's to entities
var entities = Mapper.Map(collection, await dbSet.ToListAsync());
// add new records
var toAdd = entities.Where(e => e.Id == 0);
dbSet.AddRange(toAdd);
// delete old records
var toDelete = entities.Where(entity => collection.All(e => e.Id > 0 && e.Id != entity.Id));
dbSet.RemoveRange(toDelete);
// update existing records
var toUpdate = entities.Where(entity => collection.All(i => i.Id > 0 && i.Id == entity.Id)).ToList();
foreach (var entity in toUpdate)
{
context.Entry(entity).State = EntityState.Modified;
}
await context.SaveChangesAsync();
这是我最初的问题。如果是这样,那似乎是多余的。所以我觉得我缺少一些东西。
至尊宝的传说
相关分类