MySQL Connector appending the enum with the value one less than the actual one

前端 未结 2 659
走了就别回头了
走了就别回头了 2021-01-20 05:01

I\'m using the MySQL Connector for .NET to manage a MySQL database from C#.

When I try to insert an enum into the database it appends the enum with the value

相关标签:
2条回答
  • 2021-01-20 05:21

    You could make your enum like this

    public enum MyEnum {
        FirstValue = 1, 
        SecondValue, 
        ThirdValue
    }
    

    It will start from 1 instead from 0.

    0 讨论(0)
  • 2021-01-20 05:24

    .NET enumerations are by default zero-based, and backed with an integer (i.e. you can cast a default enumeration to an integer and back).

    I imagine what is happening is that the MySQL database driver is casting the enum value to an integer, and trying to insert that.

    MySQL treats integers being inserted into enumeration columns as a 1-based index.

    I would suggest just making the database column an integer instead of a MySQL enumeration. This way, zero is a valid value.

    Alternatively, you could declare the first value of your enumeration to have an integer value of one, to match MySQL, like this:

    public enum MyEnum 
    {
        FirstValue = 1, 
        SecondValue, 
        ThirdValue
    }
    

    I think I'm right in saying that SecondValue and ThirdValue would then be backed with values 2 and 3 respectively.

    Then when the connector casts the enumeration to an integer, it will return 1, 2, and 3, which would match what MySQL expects.

    The third alternative is to keep the types as-is at both ends, and just make this mapping a function of your data layer (you do have one, right?) - then you only need to deal with this in one place. Could be a little misleading for future developers, mind.

    0 讨论(0)
提交回复
热议问题