How to convert an enum to int automatically via FastMember?
Asked Answered
P

1

6

I'm using FastMember to convert a List<T> to a Datatable. Some classes contain enums and this is causing problems when passing the datatables as a TVP to a stored procedure.

public class MyObject
{
    public int Id {get; set;}
    public SomeEnum EnumHere {get; set;}
}

var dt = new DataTable();
using (var reader = ObjectReader.Create(myObjectsList))
{
    dt.Load(reader);
}

db.Execute<ResultObject>("insert_objects", new { dt }, commandType: CommandType.StoredProcedure);

FastMember converts the list, however the column for the enum has a DataType of SomeEnum. When passing the datatable as a TVP, the following exception is thrown:

Exception thrown: 'System.ArgumentException' in Dapper.dll

Additional information: The type of column 'SomeEnum' is not supported. The type is 'SomeEnum'

Is there a way to force FastMember to convert enums to int?

Pondicherry answered 10/1, 2017 at 9:11 Comment(4)
I proposed a title edit, because the question seems trivial and like a duplicate of https://mcmap.net/q/36241/-get-int-value-from-enum-in-c/3950370Huddersfield
Could look like something that is not supported in FastMember: github.com/mgravell/fast-member/issues/10Satanism
Can you specify what kind of problems using enums causes?Huddersfield
Well, it seems like @Satanism is right. Maybe you could change the enums to ints in your data model and provide extension methods to access them as enums?Huddersfield
C
3

You can create an anonymous type to with the right properties:

var newObjects = from m in myObjectList
                 select new { m.Id, EnumHere = (int)m.EnumHere };

var dt = new DataTable();
using (var reader = ObjectReader.Create(newObjects))
{
    dt.Load(reader);
}
Cuttle answered 4/2, 2017 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.