gpt4 book ai didi

sql-server-2008 - SQLBulkCopy 与目标表中的标识插入

转载 作者:行者123 更新时间:2023-12-04 16:48:18 24 4
gpt4 key购买 nike

我正在尝试使用 SQLBulkCopy 将通用列表插入到 SQL Server,

我在身份字段方面遇到了麻烦

我希望我的目标表生成身份字段
我该怎么处理这个
这是我的代码

using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
bulkCopy.BatchSize = (int)DetailLines;
bulkCopy.DestinationTableName = "dbo.tMyTable";

var table = new DataTable();
var props = TypeDescriptor.GetProperties(typeof(tBFFormularyStatusList))
//Dirty hack to make sure we only have system data types
//i.e. filter out the relationships/collections
.Cast<PropertyDescriptor>()
.Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
.ToArray();
foreach (var propertyInfo in props)
{
bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
}

var values = new object[props.Length];
foreach (var item in myGenericList)
{
for (var i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}

table.Rows.Add(values);
}

bulkCopy.WriteToServer(table);
}

异常(exception)
Property accessor 'ID' on object 'ProcessFlatFiles.DetailsClass' threw the following exception:'Object does not match target type.'

我也试过
using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{

最佳答案

最后我以这种方式工作

    using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString, SqlBulkCopyOptions.KeepNulls & SqlBulkCopyOptions.KeepIdentity))
{
bulkCopy.BatchSize = (int)DetailLines;
bulkCopy.DestinationTableName = "dbo.myTable";
bulkCopy.ColumnMappings.Clear();
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");
.
.
.
.
bulkCopy.ColumnMappings.Add("SourceColumnName", "DestinationColumnName");

bulkCopy.WriteToServer(datatable);
}

关于sql-server-2008 - SQLBulkCopy 与目标表中的标识插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com