DataTable.Load()将枚举转换为整数

时间:2019-11-27 01:07:16

标签: c# sqlbulkcopy fastmember

我正在使用SqlBulkCopy将一些数据插入表中。我的数据对象具有一个枚举属性。我想将其另存为值(G),而不是整数(1)。

在我称为dataTable.Load()的那一点上,该属性从'G'变为1。显然就是这样吗?
https://github.com/npgsql/npgsql/issues/1220

有没有办法解决?我本来以为可能是ObjectReader的FastMember(Marc Gravell)问题,但是reader仍然具有'G'的值,所以问题是DataTable.Load()

如何将枚举另存为字符串而不是int?

    private static DataTable ToDataTable<T>(IEnumerable<T> data, List<string> columnNames)
    {
        string assemblyQualifiedName = typeof(AccrualHistory).AssemblyQualifiedName;
        Type accrualHistoryType = Type.GetType(assemblyQualifiedName);
        List<string> memberInfos = accrualHistoryType.GetMembers().Select(x => x.Name).ToList();

        // Only include properties that are *also* columns in the table.
        IEnumerable<string> propertiesThatAlsoExistInTable =
            memberInfos.Intersect(columnNames, StringComparer.OrdinalIgnoreCase);

        var dataTable = new DataTable();
        using (var reader = new ObjectReader(typeof(T), data, propertiesThatAlsoExistInTable.ToArray()))
        {
            // This is where the enum goes from 'G' to 1.
            dataTable.Load(reader); 
        }

        return dataTable;
    }

我可以尝试一些后备选项:

  • 不使用SqlBulkCopy
  • 创建一个新类并将其映射到原始类,其中新类具有enum属性作为字符串。然后使用新类保存吗?

这是枚举:

public enum FrequencyType
{
    A,     
    G
}

这是我要保存的对象的属性:

public FrequencyType FrequencyType { get; set; }

0 个答案:

没有答案