Bob Horn
Bob Horn

Reputation: 34297

DataTable.Load() Turns Enum Into Integer

I'm using SqlBulkCopy to insert some data into a table. My data object has an enum property. I want to save it as the value (G), not an int (1).

At the point where I call dataTable.Load(), the property goes from a 'G' to a 1. Apparently that's just what happens?
https://github.com/npgsql/npgsql/issues/1220

Is there a way around that? I originally thought maybe it was FastMember's (Marc Gravell) issue with ObjectReader, but reader still has the value as 'G', so it's DataTable or .Load() that's the issue.

How can I save the enum as the string and not the 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;
    }

Some fall-back options I can try:

Here's the enum:

public enum FrequencyType
{
    A,     
    G
}

And here's the property on the object I'm trying to save:

public FrequencyType FrequencyType { get; set; }

Upvotes: 0

Views: 441

Answers (0)

Related Questions