Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Linq;
- using System.Threading;
- using MongoDB.Bson.Serialization.Attributes;
- using MongoDB.Driver;
- using MongoDB.Driver.Builders;
- using MongoDB.Driver.Linq;
- using NUnit.Framework;
- using System.Collections.Generic;
- using System;
- using MongoDB.Bson;
- using MongoDB.Bson.Serialization;
- using System.Linq.Expressions;
- using MongoDB.Bson.Serialization.Conventions;
- namespace MongoDB.Groups.Repro
- {
- public static class Program
- {
- public interface IFoo
- {
- string Description { get; set; }
- }
- [Serializable]
- public class Foo : IFoo
- {
- public string Description { get; set; }
- }
- [Serializable]
- public class Bar
- {
- public ObjectId Id { get; set; }
- public IFoo MyFoo { get; set; }
- }
- public static void Main()
- {
- BsonSerializer.RegisterDiscriminatorConvention(typeof(IFoo), new FooDiscriminatorConvention());
- var server = MongoServer.Create();
- var database = server.GetDatabase("test");
- var collection = database.GetCollection<Bar>("bars");
- collection.RemoveAll();
- var docWithDiscriminator = new BsonDocument
- {
- new BsonElement("MyFoo", new BsonDocument("Description", "Blah").Add("_t", "Foo"))
- };
- var docWithOutDiscriminator = new BsonDocument
- {
- new BsonElement("MyFoo", new BsonDocument("Description", "Blah"))
- };
- collection.InsertBatch(new[] { docWithDiscriminator, docWithOutDiscriminator });
- var bars = collection.FindAll();
- }
- private class FooDiscriminatorConvention : IDiscriminatorConvention
- {
- public string ElementName
- {
- get { return "_t"; }
- }
- public Type GetActualType(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType)
- {
- var bookmark = bsonReader.GetBookmark();
- bsonReader.ReadStartDocument();
- if (bsonReader.FindElement(ElementName))
- {
- var value = bsonReader.ReadString();
- if (value != "Foo")
- {
- throw new NotSupportedException();
- }
- }
- bsonReader.ReturnToBookmark(bookmark);
- return typeof(Foo);
- }
- public BsonValue GetDiscriminator(Type nominalType, Type actualType)
- {
- return actualType.Name;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment