BsonValue.Create() creates BsonInt32 when BsonRepresentationAttribute is set to BsonType.String

533 views
Skip to first unread message

TM

unread,
May 31, 2012, 4:53:54 AM5/31/12
to mongodb-csharp
Hi,

I need many of my enums as string in the database. I'd love to have an
attribute that I could place over the enum to point out, that I want
this enum always as string, but I didn't find that. CustomTypeMapper
doesn't work for enums ether.

So I placed [BsonRepresentation(MongoDB.Bson.BsonType.String)] over
every usage of the enums.

Everything is fine while I just insert new documents, but if I update
just the enum field and use BsonValue.Create to get the value for the
update the method creates a BsonInt32 instead of a BsonString.

It would be great, if you could help me with this one.

Greets

Robert Stam

unread,
May 31, 2012, 12:14:36 PM5/31/12
to mongodb...@googlegroups.com
Simply convert your enum to a string when calling Update. For example, using this class:

    public enum E { None, A, B };

    class C
    {
        public ObjectId Id { get; set; }
        [BsonRepresentation(BsonType.String)]
        public E E { get; set; }
    }

You could Insert and then Update a document like this:

    var document = new C { E = E.A };
    collection.Insert(document);
    var id = document.Id;

    var query = Query.EQ("_id", id);
    var update = Update.Set("E", E.B.ToString()); // call ToString
    collection.Update(query, update);

In the next version of the C# driver we are introducing typed builders, which will handle serialization for you automatically. Using the current version of typed builders in the master branch your update would look like this:

    var query = Query.Build<C>(qb => qb.EQ(c => c.Id, id));
    var update = Update<C>.Set(c => c.E, E.B);
    collection.Update(query, update);

Gregor Uhlenheuer

unread,
May 31, 2012, 2:51:20 PM5/31/12
to mongodb-csharp
Hi,

I am having the same problem as described in here and especially your
second example looks really good indeed. Anyways, in a generic update
wrapper method I use I am forced to use the BsonValue.Create() method.
But even though I defined a custom type mapper for the enum type the
custom type mapper is not used because enums are treated in a special
way there.

You can find my pull request to this problem on github (https://
github.com/mongodb/mongo-csharp-driver/pull/112). If I define a custom
type mapper I expect it to be used and not being overridden by a
default enum behavior so I think this change even makes sense in a
more general way.

Cheers,
Gregor
Reply all
Reply to author
Forward
0 new messages