c# - 这是使用 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());
解决方案
它不会非常慢,但不会像批量复制那样快。选项,假设 SQL Server:
- 可以将 TVP 与 Dapper 一起使用,但唯一方便的方法是将输入数据打包到
DataTable
; Dapper repo 中有 TVP 使用的示例,或者我可以敲一个,但它们不方便,因为您需要在服务器上声明参数类型 - 您可以使用
SqlBulkCopy
独立于 Dapper 将数据放入数据库;FastMemberObjectReader
可以构造一个IDataReader
过类型的序列,适合与SqlBulkCopy
如果您不使用 SQL Server,则需要查看 RDBMS 的供应商特定选项。
推荐阅读
- javascript - 谷歌地图 - 加载标记 - 使用markercluster过滤
- dart - 使用 bloc 框架时如何为文本字段提供默认值
- sql - 获取过去 30 天内的行,不包括今天
- regex - 正则表达式来识别无括号的 if 语句
- python - 当我将它写入excel时,pandas pivot_table() 在我的数据框中放置了一个不需要的列,为什么?
- python - Pandas 子图布局在这种情况下不起作用
- r - 如何将我的列(字符)转换为 POSIXct 以创建时间序列?
- http-headers - iframe 重定向时如何传递授权标头?
- java - 会话值在 Safari 浏览器中不可用
- json - How to read an object from an script of index.html in angular