Hi,
I'm trying to do a RegisterType for an enum type to convert it into an integer before saving it... mainly to save on space. Holding 50k+ rows with a lengthy string value for an enum seems like a bit of a waste to me. It appears to be getting ignored, though. Any ideas? Maybe I'm missing something really simple but I'm not sure what.
Thanks!
```c#
enum SomeType
{
SOME_SUPER_LONG_ENUM_NAME,
MAYBE_A_SHORTER_NAME,
}
BsonMapper.Global.RegisterType
serialize: (s) => ((int)s).ToString(),
deserialize: (bson) => {
return (SomeType)Enum.Parse(typeof(SomeType), bson);
}
);
```
Custom serialization works only after basic data types (and enum are basic datatype). You can check here:
https://github.com/mbdavid/LiteDB/blob/master/LiteDB/Mapper/BsonMapper.Serialize.cs#L92
But you can write a custom property serialization/deserialization method. Like this:
```C#
BsonMapper.Global.ResolveMember = (type, memberInfo, memberMapper) =>
{
if (memberMapper.MemberName == "MyPropertyName")
{
// Convert your enum into "int"
memberMapper.Serialize = (obj, mapper) => new BsonValue((int)obj);
// Convert int into enum
memberMapper.Deserialize = (value, mapper) => (SomeType)Enum.Parse(typeof(SomeType), value);
}
}
```
This ResolveMember is an way to capture all map options for all types. This is called during mapping object into document.
https://github.com/mbdavid/LiteDB/blob/master/LiteDB/Mapper/BsonMapper.cs#L315
Thanks for this! It's a great starting point. Might be good to note on the wiki too, might be something others might be interested in doing as well.
Much appreciated!
It would be great if that could be an option as a default setting.
It's great that it can be overwritten with the mapper, but an option to apply for all primitive types of enum would be a lot more convenient, maybe for v5?
Hi,
I agree with @Aranir . It would be great if for v5 there would be an option to set if we want enum to be saved as string or int.
In my opinion int is better, because most of the time I change the name of the enum value, for better readability of the code, rather than the value.
Thanks in advance
@darcome This feature is avaliable in LiteDB v5. If you're using the global mapper, you can configure it to treat enums as ints with the following command:
C#
BsonMapper.Global.EnumAsInteger = true;
@lbnascimento Thank you very much for your answer! This is great!
@darcome Can we assume that your questions have been answered? If so, could you please close the ticket because it's hard to keep track of relevant issues if the answered ones stay open ;)
Most helpful comment
@darcome This feature is avaliable in LiteDB v5. If you're using the global mapper, you can configure it to treat enums as ints with the following command:
C# BsonMapper.Global.EnumAsInteger = true;