Created
February 25, 2011 16:45
-
-
Save jakejscott/844064 to your computer and use it in GitHub Desktop.
Simple.Data.MongoDb dynamics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Things.IO.Mongo | |
{ | |
using System; | |
using MongoDB.Bson.Serialization; | |
using MongoDB.Driver; | |
using NUnit.Framework; | |
using Simple.Data; | |
using Simple.Data.MongoDb; | |
internal static class DatabaseHelper | |
{ | |
static DatabaseHelper() | |
{ | |
BsonSerializer.SerializationProvider = new DynamicSerializationProvider(); | |
} | |
public static dynamic Open() | |
{ | |
return Database.Opener.OpenMongo("mongodb://localhost/simpleDataTests?safe=true"); | |
} | |
public static void Reset() | |
{ | |
var server = MongoServer.Create("mongodb://localhost/?safe=true"); | |
server.Connect(); | |
server.DropDatabase("simpleDataTests"); | |
InsertData(server.GetDatabase("simpleDataTests")); | |
} | |
private static void InsertData(MongoDatabase db) | |
{ | |
var listings = new[] | |
{ | |
new Listing {Id = 1, Title = "Bike", Description = "Mountain bike", | |
Fields = new { | |
Color = "Red", | |
ManufactureDate = new DateTime(2001, 1, 1) | |
} | |
}, | |
new Listing {Id = 2, Title = "Toast", Description = "Burnt to the crisp", | |
Fields = new { | |
NukeFactor = "Mental", | |
PowerRating = 10000 | |
} | |
} | |
}; | |
db.GetCollection("Listings").InsertBatch(listings); | |
} | |
} | |
public class Listing | |
{ | |
public int Id { get; set; } | |
public string Title { get; set; } | |
public string Description { get; set; } | |
public dynamic Fields { get; set; } | |
public override string ToString() | |
{ | |
return string.Format("Id: {0}, Title: {1}, Description: {2}", Id, Title, Description); | |
} | |
} | |
[TestFixture] | |
public class MongoThings | |
{ | |
[TestFixtureSetUp] | |
public void Setup() | |
{ | |
DatabaseHelper.Reset(); | |
} | |
[Test] | |
public void DynamicSupport() | |
{ | |
var db = DatabaseHelper.Open(); | |
Listing listing = db.Listings.FindById(1); | |
Assert.NotNull(listing); | |
// Static fields | |
Assert.That(listing.Title, Is.EqualTo("Bike")); | |
Assert.That(listing.Description, Is.EqualTo("Mountain bike")); | |
// Dynamic fields | |
Assert.That(listing.Fields.Color, Is.EqualTo("Red")); | |
Assert.That(listing.Fields.ManufactureDate, Is.EqualTo(new DateTime(2001, 1, 1))); | |
Console.WriteLine("Inserted listing " + listing); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment