以不同的方式询问相同的问题!似乎很明显,我需要详细说明这个问题,因为我没有可行的答案。基于此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();这是我最初的问题。如果是这样,那似乎是多余的。所以我觉得我缺少一些东西。
1 回答
至尊宝的传说
TA贡献1789条经验 获得超10个赞
EFDbSet
不是集合。基本上,它们代表数据库表并为其提供查询和DML操作。
看起来您想将整个表与DTO列表同步。您可以通过使用Load
或LoadAsync
方法在本地加载整个表,然后Map
将DTO集合加载到entityDbSet.Local
属性来实现。你尝试不同的是,该Local
属性不是一个简单的列表,但观察到的集合直接绑定到上下文本地存储和变更跟踪器,所以任何修改(Add
,Remove
)将被应用到数据库。
像这样的东西:
await dbSet.LoadAsync();
Mapper.Map(dtoCollection, dbSet.Local);
await context.SaveChangesAsync();
- 1 回答
- 0 关注
- 155 浏览
添加回答
举报
0/150
提交
取消