Skip to content

Instantly share code, notes, and snippets.

@sindbach
Last active April 15, 2020 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sindbach/4234caa968f059c6a897c4088d6b98b0 to your computer and use it in GitHub Desktop.
Save sindbach/4234caa968f059c6a897c4088d6b98b0 to your computer and use it in GitHub Desktop.
MongoDB .NET/C# Polymorphism BsonKnownTypes
using System;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Bson.Serialization.Attributes;
using System.Collections.Generic;
namespace Application
{
[BsonKnownTypes(typeof(Cat), typeof(Dog))]
public class Pet
{
public string Name {get; set;}
}
public class Cat : Pet
{
public string Toy {get; set;}
}
public class Dog : Pet
{
public string Toy {get; set;}
}
public class House
{
public ObjectId Id {get; set;}
public List<Pet> Pets {get; set;}
}
class Program
{
static void Main(string[] args)
{
var mongoURL = new MongoUrl("mongodb://localhost:27017/test");
var client = new MongoClient(mongoURL);
var database = client.GetDatabase("test");
var collection = database.GetCollection<House>("myhouse");
/* Part A: Serialize */
var mypets = new List<Pet>();
mypets.Add(new Cat{ Name="Izzy", Toy="scratchy"} );
mypets.Add(new Dog{ Name="Dotty", Toy="plushy"} );
collection.InsertOne(new House { Pets=mypets});
/* Part B: Deserialize */
var document = collection.Find<House>(new BsonDocument()).FirstOrDefault();
Console.WriteLine(document.ToJson());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment