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

痞子三分冷 提交于 2019-12-01 20:59:55

.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.

You could make your enum like this

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

It will start from 1 instead from 0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!