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

C# Entity Framework 批量插入数据:SQL语句转LINQ查询方法

Entity Framework 对应实现方案

方案1:EF Core 7.0 及以上版本(推荐,接近原生SQL性能)

EF Core 7.0开始原生支持批量插入操作,无需将数据加载到应用内存即可生成等效的原生SQL执行,对应LINQ写法如下:

await dbContext.Services
    .GroupBy(s => new { s.Id, s.Type })
    .Select(g => new 
    {
        ClientId = g.Key.Id,
        ServerId = g.Key.Type,
        Count = g.Count()
    })
    .ExecuteInsertAsync(
        target => target.Servers,
        (source, target) => new Server
        {
            ClientId = source.ClientId,
            ServerId = source.ServerId,
            Count = source.Count
        });

方案2:EF 6 或 EF Core 7以下版本

低版本EF没有原生批量插入API,需要先查询得到分组结果,再批量添加到数据集后提交,写法如下:

// 查询分组后的待插入数据
var insertList = dbContext.Services
    .GroupBy(s => new { s.Id, s.Type })
    .Select(g => new Server
    {
        ClientId = g.Key.Id,
        ServerId = g.Key.Type,
        Count = g.Count()
    })
    .ToList();

// 批量添加实体
dbContext.Servers.AddRange(insertList);
// 提交事务写入数据库
await dbContext.SaveChangesAsync();

注意事项

  • 方案2会将所有待插入数据加载到应用内存,数据量大时性能远低于原生SQL,这种场景建议直接调用dbContext.Database.ExecuteSqlRaw()执行你原有的原生SQL语句,性能最优。
  • 请确保实体属性和数据库字段的映射关系配置正确,避免插入时字段对应错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:36:02