如何使用快速成员将数据批量复制到具有不一致列名称的表中?

时间:2015-03-18 16:30:43

标签: c# fastmember

我有一个Person表,其中包含以下列名:

  

我,姓名,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在运行时检索表元数据,而FastMember则在运行时再次使用ObjectReader。 / p>

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:5)

最后它变得比我想象的要简单得多:

// 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);
}

答案 1 :(得分:1)

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

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

然后

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