如何使用 Fast Member 将数据批量复制到列名不一致的 table 中?

How can I use Fast Member to Bulk Copy data into a table with inconsistent column names?

我有一个 Person table 以下列名称:

Id, Name, Dob

我也有一个 poco 作为:

public class Person
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string DateOfBirth {get; set;}
}

我正在尝试:

var people = new List<Person>();
... // added a bunch of people

using (var bcp = new SqlBulkCopy(sqlConnection, SqlBulkCopyOptions.TableLock, transaction))
using (var reader = ObjectReader.Create(people, "Id", "Name", "Dob"))
{
    bcp.BulkCopyTimeout = 120;
    bcp.BatchSize = 0;
    bcp.DestinationTableName = "Person";
    bcp.WriteToServer(reader);
}

但是,由于列名 Dob 与 属性 名称不匹配 DateOfBirth 我收到 FastMember 抛出的 Index out of range,我该如何解决问题而不必重命名 属性 或列。

请注意,我需要一个可以同时使用 属性 和仅在 运行 时间已知的列名称的答案,因为我目前正在使用 ServiceStack Ormlite 检索 table 元数据在 运行 时间和 FastMember 在 运行 时间再次进入 ObjectReader。

非常感谢任何帮助。

使用简单的 LINQ 投影,您可以:

var people2 = people.Select(x => new { x.Id, x.Name, Dob = x.DateOfBirth });

然后

using (var reader = ObjectReader.Create(people2, "Id", "Name", "Dob"))

最后发现比我想象的简单多了:

// Get valid columns from the [targetTable] on the db at runtime
// and produce a simple mapping
// validColumns is an IDictionary<string, string>
var membersExposedToReader = validColumns.Keys.ToArray();

// data is an IEnumerable<T>           
using (var bcp = new SqlBulkCopy(sqlConnection, SqlBulkCopyOptions.TableLock, tran))
using (var reader = ObjectReader.Create(data, membersExposedToReader))
{
    foreach (var member in membersExposedToReader)
    {
        bcp.ColumnMappings.Add(member, validColumns[member]);
    }

    bcp.BulkCopyTimeout = 120;
    bcp.BatchSize = 0;
    bcp.DestinationTableName = targetTable;
    bcp.WriteToServer(reader);
}