You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Entity Framework Core中批量添加子ID至数据库的实现方案

我来帮你搞定这个批量添加的问题,核心思路是先调整视图模型来接收子ID数组,再在服务层循环生成对应实体并批量插入数据库。具体步骤如下:

1. 修改视图模型以接收子ID列表

首先要更新CategoryRollupViewModel,把单个的CategoryChildID改成列表类型,这样才能接收前端传来的数组:

public class CategoryRollupViewModel {
    [Key]
    public int ID { get; set; }
    // 改为List<int>接收多个子ID
    public List<int> CategoryChildID { get; set; }
    public int CategoryParentID { get; set; }
}

2. 调整服务层的批量添加逻辑

接下来修改Add方法,遍历每个子ID创建对应的CategoryRollup实体,再用AddRange批量添加(比逐个Add更高效):

public async Task<ServiceResultWithoutBaseEntity<CategoryRollup>> Add(CategoryRollupViewModel newItem) {
    var result = new ServiceResultWithoutBaseEntity<CategoryRollup>();
    result.Errors.AddRange(Validate(newItem));
    if (result.HasErrors) return result;

    // 为每个子ID生成一条实体记录
    var rollupEntities = newItem.CategoryChildID.Select(childId => new CategoryRollup {
        CategoryChildID = childId,
        CategoryParentID = newItem.CategoryParentID
    }).ToList();

    // 批量添加到数据库上下文
    _context.CategoryRollups.AddRange(rollupEntities);
    await _context.SaveChangesAsync();

    // 返回结果可根据需求调整,比如返回第一条或整个列表
    result.EntityResult = rollupEntities.FirstOrDefault();
    return result;
}

3. 补充验证逻辑(关键)

记得在Validate方法里添加对CategoryChildID列表的校验,避免空列表或无效数据:

public IEnumerable<string> Validate(CategoryRollupViewModel model) {
    if (model.CategoryChildID == null || !model.CategoryChildID.Any()) {
        yield return "CategoryChildID列表不能为空";
    }
    // 保留原有其他验证逻辑...
}

4. 可选:优化映射助手类(复用逻辑)

如果想保留映射助手的复用性,可以新增一个批量映射方法:

public static class CategoryRollupHelper {
    // 保留原有单个实体映射方法...

    // 新增批量映射方法
    public static List<CategoryRollup> MapToEntities(this CategoryRollupViewModel source) {
        if (source == null || source.CategoryChildID == null) return new List<CategoryRollup>();
        
        return source.CategoryChildID.Select(childId => new CategoryRollup {
            CategoryChildID = childId,
            CategoryParentID = source.CategoryParentID
        }).ToList();
    }
}

之后在服务层就能直接调用:

var rollupEntities = newItem.MapToEntities();

调整完成后,当收到{"CategoryParentID": "4", "CategoryChildID": [5,6,7]}这样的JSON时,服务层会自动为每个子ID生成一条数据库记录,一次性提交操作,既解决了EF不支持原始类型列表的问题,又保证了插入效率。

内容的提问来源于stack exchange,提问作者user10860402

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:04:24