简洁的插入或更新?

问题描述 投票:0回答:1

我还没有开始使用 Dapper,但今天在研究批量插入/更新时偶然发现了它。目前我正在使用 EF6,但我希望在未来的批量处理中使用 Dapper。对于这个应用程序,可能有大约 15k 条记录,但我有其他应用程序可能有大约 100k 条记录。

我正在尝试研究一种将以下 EF 代码转换为 Dapper 的方法。它所做的只是从文件中读取记录,查看该员工是否存在于数据库中,如果存在,则使用文件中的值更新属性,如果不存在,则使用文件中的值创建一个新对象。

我四处寻找时找不到任何例子。我所能找到的只是如何进行简单的插入或更新。我确实没有找到批量插入/更新的好例子。很可能我只是还不明白如何使用 Dapper。

我该如何使用 Dapper 来做到这一点?

int count = 1;
using (ctx = new DataContext())
{
    ctx.Configuration.AutoDetectChangesEnabled = false;      
    ctx.Configuration.ValidateOnSaveEnabled = false;

    while ((record = srFile.ReadLine()) != null)
    {
        int employeeId = int.Parse(record.Substring(2, 8));

        bio_employee employee = ctx.bio_employee.FirstOrDefault(e => e.emp_id == employeeId);

        if (employee != null)
        {
            SetEmployeeData(employee, record);

            ctx.Entry(employee).State = System.Data.Entity.EntityState.Modified;
        }
        else
        {
            employee = new bio_employee();
            employee.emp_id = employeeId;

            SetEmployeeData(employee, record);

            ctx.bio_employee.Add(employee);
        }


        if (count % batchSize == 0)
        {
            ctx.SaveChanges();
            ctx.Dispose();
            ctx = new DataContext();
        }

        count++;
    }
    ctx.SaveChanges();      //save any remaining
}
dapper
1个回答
11
投票

Dapper 提供了多种查询数据的方法,但除了使用通常没有 ORM 的命令之外,没有其他方法可以执行保存操作。

许多第三方库都涵盖了 Dapper 的这种情况:

免责声明:我是该项目的所有者Dapper Plus

Dapper Plus 是迄今为止最快的库,提供:BulkInsert、BulkDelete、BulkUpdate 和 BulkMerge 操作。轻松支持百万条记录场景

// CONFIGURE & MAP entity
DapperPlusManager.Entity<Employee>()
                 .Table("Employee")
                 .Identity(x => x.EmployeeID);

// SAVE entity
connection.BulkMerge(employeeList);

编辑:回答子问题

您的 DapperPlus 中的 .BulkMerge 是否正在执行更新插入

是的,BulkMerge 是一个更新插入操作。

您还可以使用映射键为同一实体指定多个映射。

// Using key from database (x => x.EmployeeID)
DapperPlusManager.Entity<Employee>()
                 .Table("Employee");

connection.BulkInsert(employees);

// Using custom key
DapperPlusManager.Entity<Employee>("customKey")
                 .Table("Employee")
                 .Key(x => x.Code);

connection.BulkInsert("customKey", employees);
© www.soinside.com 2019 - 2024. All rights reserved.