Best way to work with c# enum

Hi Everybody,

I would like to work with enum in c#.
I tried to implement a custom serializer like this :

[BsonSerializer(typeof(MySerializer))]
    public class MyClass
    {....

public class MySerializer : IBsonSerializer
    {...

And when I tried to call GetCollection on this line :

var test = database.GetCollection<MyClass>(settings.CollectionName);

I receive an error :

Unable to cast object of type ‘Manager.Api.Models.MySerializer’ to type ‘MongoDB.Bson.Serialization.IBsonSerializer`1[Manager.Api.Models.MyClass]’.

Did I forget something?

Thanks.
Best Regards,
Thierry

Hi @Thierry7, and welcome to the forum!

An example class mapping with enum would be as below:

public class MyClass 
{
    public MyType MyType {get;set;}
    public string FooBar {get;set;}
}

// Example enum strings
public enum MyType 
{
    [BsonRepresentation(BsonType.String)]
    TypeA, 
    [BsonRepresentation(BsonType.String)]
    TypeB, 
    [BsonRepresentation(BsonType.String)]
    Default,
}

If you have further question, could you provide:

  • MongoDB .NET/C# version
  • Example documents
  • Minimal reproducible code example
  • Expected outcome of the code example

Regards,
Wan.

2 Likes

Hi @wan , thanks for your the clarification, do you happen to know which is the best way to fix the enums representation in “swashbuckle.aspnetcore” swagger generator?

This is my Enum:
namespace ApmAPI.Models
{
public enum OnboardingState
{

        CREATED,

        
        UPLOADING,

        
        PROCESSING,

        
        ONBOARDED
    }
}

But in Swagger i get only the following:

OnboardingStateinteger($int32)
Enum:
[ 0, 1, 2, 3 ]

In my non - mongo implementation i would use something like the below to have enums appear correctly

image
Thanks a lot !

Ok found the way !! It’s documented in the following , there is no need to add any annotations in your enums

https://github.com/domaindrivendev/Swashbuckle.AspNetCore#systemtextjson-stj-vs-newtonsoft

1 Like