0
votes

I am implementing a mongodb cache for this asp.net webapi output cache (I agree redis would be better / faster but for now, I need a mongodb implementation!)

Anyway,

I have a CachedItem class that holds my key / value:

[BsonIgnoreExtraElements]
public class CachedItem
{
    [BsonElement("key")]
    public string Key { get; set; }

    [BsonElement("value")]
    public object Value { get; set; }
}

Value is an object, that could be anything, we don't control that.

In one of my tests, I have a very simple poco:

public class UserFixture
{
    public UserFixture()
    {
        Id = Guid.NewGuid();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}

When this is set to the Value it is serialized and persisted.

When I try to retrieve it, it fails to deserialize, as it has automatically grabbed the "Id" property.

An error occurred while deserializing the Id property of class WebAPI.OutputCache.MongoDb.Tests.UserFixture: Cannot deserialize Guid from BsonType ObjectId

Obviously, I can't decorate UserFixture

Is there any way I can tell MongoDB driver to basically serialize CachedItem.Value, as say, a string?

I could use JSON.net to do this before saving, and deserialize it on the way back out, but I was hoping to avoid this.

It's also on GitHub That link should take you straight to the relevent commit if you'd like to try the failing test.

1
I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not".John Saunders
Cool, although 'serialize' 'class' 'object' and 'string' are all tags on SO too... so I wouldn't be too vigorous on keeping up this best-practice! ;)Alex

1 Answers

1
votes

You can of course tell MongoDB to serialize your class as a string by building your own custom BsonSerializer. I have found it easier to inherit from their BsonStringSerializer. You also need to register that serializer with your specific type. (I suggest using a BsonSerializationProvider for that)

What you do need to think about is how to represent all your possible data as a string so you could deserialize it back to your application (Consider for example that you probably need to save the type information).