首页 > 解决方案 > 这是使用 Dapper 进行批量插入的有效方法吗?

问题描述

这是使用 Dapper 进行批量插入的有效方法吗?

此外,这是否比创建存储过程并将模型传递给它更有效?

这是使用 Dapper 进行批量插入的有效方法吗?

此外,这是否比创建存储过程并将模型传递给它更有效?

category = new Category
           {
               Name = "category",
               Description = "description",
               Created = null,
               LastModified = null,
               CategoryPictures = new CategoryPicture[]
               {
                    new CategoryPicture
                    {
                        CategoryId = 3,
                        PictureId = 2,
                        Picture = new Picture
                        {
                            Url = "newUrl"
                        }
                    },
                      new CategoryPicture
                    {
                        CategoryId = 3,
                        PictureId = 2,
                        Picture = new Picture
                        {
                            Url = "url"
                        }
                    }
                }
            };

string sql = @"INSERT INTO Categories(Name, Description, Created, LastModified)
               VALUES(@Name, @Description, @Created, @LastModified)";

await conn.ExecuteAsync(sql, new
            {
                category.Name,
                category.Description,
                category.Created,
                category.LastModified
            });

string catPicInsert = @"INSERT INTO CategoryPictures(fk_CategoryId, fk_PictureId)
                        VALUES(@CategoryId, @PictureId)";

await conn.ExecuteAsync(catPicInsert, category.CategoryPictures);

string PicInsert = @"INSERT INTO Pictures(Url)
                     VALUES(@Url)";

await conn.ExecuteAsync(PicInsert, category.CategoryPictures.Select(x => x.Picture).ToList());

标签: c#.netdatabaseinsertdapper

解决方案


它不会非常慢,但不会像批量复制那样快。选项,假设 SQL Server:

  • 可以将 TVP 与 Dapper 一起使用,但唯一方便的方法是将输入数据打包到DataTable; Dapper repo 中有 TVP 使用的示例,或者我可以敲一个,但它们不方便,因为您需要在服务器上声明参数类型
  • 您可以使用SqlBulkCopy独立于 Dapper 将数据放入数据库;FastMemberObjectReader可以构造一个IDataReader过类型的序列,适合与SqlBulkCopy

如果您不使用 SQL Server,则需要查看 RDBMS 的供应商特定选项。


推荐阅读