MongoRepository icon indicating copy to clipboard operation
MongoRepository copied to clipboard

Certain value types serializing as binary?

Open dasjestyr opened this issue 8 years ago • 3 comments

So I'm just trying this out for the first time and I noticed that types like Guid and DateTimeOffset were getting serialized as binary blobs and/or byte arrays. Is that normal? I would have thought they would have called ToString() before storing or something.

dasjestyr avatar Jan 09 '17 00:01 dasjestyr

You can use an attribute (for example: a BsonDateTimeOptions attribute) to change the serializiation to your needs (in this example the attribute can be used to specify you would only want to serialize the date-'part' for example and ignore the time-'part'). This is not something MongoRepository provides but is provided by the underlying mongo-csharp-driver. You can find documentation here. You can also use conventions (see here) which are, again, something provided by the underlying mongo-csharp-driver.

I would, however, advice to use the 'binary blob' unless you have a very specific and good reason to want to serialize to string.

RobThree avatar Jan 09 '17 10:01 RobThree

I would, however, advice to use the 'binary blob' unless you have a very specific and good reason to want to serialize to string.

Not sure how I'd query on binary...

I'll look into these other things. Thanks!

dasjestyr avatar Jan 10 '17 02:01 dasjestyr

Not sure how I'd query on binary...

If you store an object:

class MyObject : Entity {
    public Guid SomeProperty { get; set; }
}

var myrepo = new MongoRepository<MyObject>();

var someguid = Guid.NewGuid();
var x = new MyObject { SomeProperty = someguid };

// Save object
myrepo.Update(x);

You can simply query it like this:

myrepo.Where(o => o.SomeProperty == someguid);

(Code written on the fly; may contain some (syntax)errors).

If you want to query it from other platforms you can query it with something like:

db.collection.find({ "SomeProperty": new BinData(3, "MSlQ8XxCwE6I9tCqLtXy9g==")})

Where MSIQ....y9g== is the Base64 representation of the GUID; this may differ for other datatypes like datetime which would be something like:

db.collection.find({ "SomeProperty": ISODate("2016-10-20T15:23:11Z")})

But unless you write your queries 'manually' like in the above format MongoRepository (actually the underlying driver) should take care of it.

See also here and here and here for more info.

RobThree avatar Jan 10 '17 09:01 RobThree