如何将列添加到DataReader的 [英] How to add columns to DataReader
问题描述
我的目标是从数据源中检索数据,添加一些元数据,并将其插入到另一个目标。
My goal is to retrieve data from a data source, add some metadata to it and insert it to another target.
目标有四个列的模式,然后源(计算列)。
The target has schema with four more columns then the source (calculated columns).
我使用的使用SqlBulkCopy ,它需要与所有列(包括计算4)阅读器。
I am using SqlBulkCopy, which requires a reader with all columns (including the 4 calculated).
有没有办法将列手动添加到DataReader的?或如果它是不可能的,我有什么选择的数据插入?
Is there a way to add columns to the DataReader manually? or if it's not possible what alternatives i have for the data insertion?
推荐答案
有可能的。
- 创建自己的类实现IDataReader的接口
- 添加现有的DataReader在类的构造函数
- 根据需要从基础的DataReader或返回返回结果覆盖接口你自己的计算值
只是为了得到一个想法,这可能是一个简单的实现(我跳过大多数方法)
Just to get an idea, this could be a simple implementation (I skipped most methods)
public class WrapperDataReader : IDataReader
{
private IDataReader reader;
public WrapperDataReader(IDataReader reader)
{
this.reader = reader;
}
public void Close()
{
reader.Close();
}
public int Depth
{
get { return reader.Depth; }
}
public DataTable GetSchemaTable()
{
var schemaTable = reader.GetSchemaTable();
// add your computed column to the schema table
schemaTable.Rows.Add(...);
return schemaTable;
}
public bool GetBoolean(int i)
{
return reader.GetBoolean(i);
}
public int GetOrdinal(string name)
{
if (name.Equals("displayName", StringComparison.InvariantCultureIgnoreCase))
return 15;
return reader.GetOrdinal(name);
}
public string GetString(int i)
{
if (i == 15)
return String.Format("{0}, {1}", GetString(1), GetString(2)); // lastname, firstname
return reader.GetString(i);
}
}
更新
由于正在propably使用在WriteToServer方法,可以使用接受一个DataTable重载代替。
Since you are propably using the WriteToServer method, you can use the overload that takes a DataTable instead.
var connectionString = "...";
var copy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default);
copy.DestinationTableName = "Customers";
var reader = new SqlDataReader();
var table = new DataTable();
table.Load(reader);
table.Columns.Add("DisplayName", typeof(string), "lastname, firstname");
table.Columns.Add("CustomerCode", typeof(string));
foreach (DataRow row in table.Rows)
row["CustomerCode"] = ((int)row["id"] + 10000).ToString();
copy.WriteToServer(table);
这篇关于如何将列添加到DataReader的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!