Enum and Flags support in ormlite servicestack
Asked Answered
C

2

8

Due to my error message:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Conversion failed when converting the nvarchar value 'AB' to data type int.

I have an enum with an AB value and I want to save it as integer not nvarchar value. I have an enum with flags attribute something like: [Flags]

public enum VisibleDayOfWeek : int
{
    None = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 4,
    Thursday = 8,
    Friday = 16,
    Saturday = 32,
    Sunday = 64
}

I can not save multiple day string in the db but I can save the sum of the flags values which represent multiple days.

I do not want to create an integer wrapper around these enum properties.

The underlying type of an enum is a byte or integer so why the heck is it saved as string/varchar? That makes no sense. Even the entity framework got it right with its enum support after years...

What is the solution in this case?

Seems this guy has the same problem: https://github.com/tapmantwo/enumflags

Credential answered 20/12, 2013 at 20:53 Comment(0)
A
6

Late answer, but in v4.0.8 the [Flags] attribute was added to enums, which makes ServiceStack always treat the emum as int.

From v4.0.54 you can also now use the [EnumAsInt] attribute which will save the enum to database as an int in OrmLite but when serializing it will do so as a string.

Adames answered 5/3, 2016 at 3:13 Comment(0)
M
5

As far as I know ormlite version 3 doesnt support enum, who know about next version. any way your solution there is just to use integer wrapper

public int VisibleDayOfWeek { get; set; }

[Ignored]
public VisibleDayOfWeek VisibleDayOfWeekEnum
{
    get { return (VisibleDayOfWeek)VisibleDayOfWeek; }
    set { VisibleDayOfWeek = (int)value; }
}

Even the entity framework got it right with its enum support after years

entity framework have enum support after version > 4, also you shouldn't expect to much entity framework is rich featured while ormlite is just just like its name 'lite'.

Mcmann answered 22/12, 2013 at 11:23 Comment(3)
As said before in my question I do not want an integer wrapper. And in many parts ormlite is more rich than EF. EF has no Partial update or Expression based API for Update, Delete and much more. And Ormlite v4 is out for a while.Credential
It's because you only take ormlite feature that ef doesn't have, if you take ef feature that ormlite doesn't ef have much more. There's no other solution other than integer wrapper or maybe fork ormlite, and make it support Enum.Mcmann
The Flags is already reported as bug. Now I wait that the author also will confirm that enum value to string and not to int is seen as a bug. github.com/ServiceStack/ServiceStack.OrmLite/commit/…Credential

© 2022 - 2024 — McMap. All rights reserved.