我有一个应用程序用于将大量数据(每个文件最多约 250,000 条记录)从文件插入到具有多个计算列的表中。有什么方法可以选择哪些列 fastmember 插入数据,这样我就不会尝试写入计算列?
1645 次
2 回答
1
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);
}
}
于 2017-02-04T00:38:45.597 回答
0
型号类:
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);
}
于 2018-03-29T15:52:16.157 回答