Skip to content

Instantly share code, notes, and snippets.

@rstam
Created December 17, 2010 15:02
Show Gist options
  • Save rstam/745065 to your computer and use it in GitHub Desktop.
Save rstam/745065 to your computer and use it in GitHub Desktop.
TestSerializeUserIdAsInt.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.DefaultSerializer;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
namespace TestSerializeUserIdAsInt {
public class UserId {
static UserId() {
BsonSerializer.RegisterSerializer(typeof(UserId), new UserIdSerializer());
}
public int Id { get; set; }
public UserId(int id) {
Id = id;
}
}
public class User {
[BsonId]
public UserId UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class UserIdSerializer : BsonBaseSerializer {
public override object Deserialize(BsonReader bsonReader, Type nominalType) {
return new UserId(bsonReader.ReadInt32());
}
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, bool serializeIdFirst) {
var userId = (UserId) value;
bsonWriter.WriteInt32(userId.Id);
}
}
public static class Program {
public static void Main(string[] args) {
var server = MongoServer.Create("mongodb://localhost/?safe=true");
var database = server["test"];
var users = database.GetCollection<User>("users");
var user = new User { UserId = new UserId(5678), FirstName = "John", LastName = "Doe" };
users.RemoveAll();
users.Insert(user);
user = users.FindOne();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment