How to save enums as strings?
Closed this issue · 2 comments
cryodream commented
Hi,
I want to ask, how do I force the MongoRepository to save enums to the mongodb as strings, instead of numbers?
RobThree commented
Remember MongoRepository is simply an abstraction on top of the Mongo C# driver. So you'd use something like this and this works fine with MongoRepository:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoRepository;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var repo = new MongoRepository<Person>();
repo.Add(new Person { Name = "Rob Janssen", Gender = Gender.Male });
var test = repo.First();
}
}
public enum Gender
{
Male,
Female
}
public class Person : Entity
{
[BsonRepresentation(BsonType.String)]
public Gender Gender { get; set; }
public string Name { get; set; }
}
Gives us:
{
"_id" : ObjectId("567328e66c393742f4eeb06c"),
"Gender" : "Male",
"Name" : "Rob Janssen"
}
cryodream commented
Thank you so much.