使用Fastmember只大容量插入选定的列
本文关键字:插入 Fastmember 大容量 使用 | 更新日期: 2023-09-27 17:57:43
我有一个应用程序,用于将大量数据(每个文件最多约250000条记录)从一个文件插入到一个具有多个计算列的表中。有没有办法选择fastmember插入数据的列,这样我就不会尝试写入计算列了?
using (SqlBulkCopy bcp = new SqlBulkCopy(YourConnectionString))
{
// +1 to Marc Gravell for this neat little library to do the mapping for us
// because DataTable isn't available until .NET Standard Library 2.0
using (var dataReader = ObjectReader.Create(yourListOfObjects,
nameof(YourClass.Property1),
nameof(YourClass.Property2)))
{
bcp.DestinationTableName = "YourTableNameInSQL";
bcp.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Property1", "MyCorrespondingTableColumn"));
bcp.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Property2", "TableProperty2"));
await bcp.WriteToServerAsync(dataReader).ConfigureAwait(false);
}
}
型号类别:
class ExampleModel
{
public int property1 { get; set; }
public string property2 { get; set; }
public string property3 { get; set; }
}
型号列表:
private List<ExampleModel> listOfObject = new List<ExampleModel>()
{
new ExampleModel { property1 = 1, property2 = 'Rudra', property3 = 'M'},
new ExampleModel { property1 = 2, property2 = 'Shivam', property3 = 'M'}
};
使用具有列映射的Fastmember批量插入:
using (var bcp = new SqlBulkCopy(SQLConnectionString))
using (var reader = ObjectReader.Create(listOfObject))
{
bcp.DestinationTableName = "[dbo].[tablename]";
bcp.ColumnMappings.Add("property1", "tableCol1");
bcp.ColumnMappings.Add("property2", "tableCol2");
bcp.ColumnMappings.Add("property3", "tableCol3");
bcp.WriteToServer(reader);
}
记住:
插入带有标识字段的数据—不要忘记使用KeepIdentity。
using (var bcp = new SqlBulkCopy(SQLConnectionString, SqlBulkCopyOptions.KeepIdentity))
插入具有自动递增标识字段的数据,删除自动递增列映射字段。类似于property1是数据库中的自动递增列,所以在插入数据时跳过此列。
using (var bcp = new SqlBulkCopy(SQLConnectionString))
using (var reader = ObjectReader.Create(listOfObject))
{
bcp.DestinationTableName = "[dbo].[tablename]";
bcp.ColumnMappings.Add("property2", "tableCol2");
bcp.ColumnMappings.Add("property3", "tableCol3");
bcp.WriteToServer(reader);
}