private static void RegisterClassMaps(IEnumerable<Type> clrTypes) { foreach (var clrType in clrTypes) { if (clrTypes.Any(x => x.BaseType.Name == clrType.Name)) { var genericSetIsRootClassMethod = MongoDBDataServiceFactorySetIsRootClassMethod.MakeGenericMethod(clrType); var genericBsonClassMap = typeof(BsonClassMap<>).MakeGenericType(clrType); var actionT = typeof(Action<>).MakeGenericType(genericBsonClassMap); var @delegate = Delegate.CreateDelegate(actionT, genericSetIsRootClassMethod); RegisterClassMapWithExpressionMethod.MakeGenericMethod(clrType).Invoke(typeof(BsonClassMap), new object[] { @delegate }); } else { RegisterClassMapWithoutExpressionMethod.MakeGenericMethod(clrType).Invoke(typeof(BsonClassMap), new object[] { }); } } } private static void SetIsRootClass<T>(BsonClassMap<T> map) { map.SetIsRootClass(true); } // 忽略未绑定字段, 例如 mongodb 自带的 _id,否则查询时反序列化会报错,提示在 type 中找不到 _id 字段 private static void IgnoreExtraElements() { var pack = new ConventionPack { new IgnoreExtraElementsConvention(true) }; ConventionRegistry.Register("My Solution Conventions", pack, t => true); } private static readonly MethodInfo RegisterClassMapWithExpressionMethod = typeof(BsonClassMap).GetMethods().Where(x => x.Name == nameof(BsonClassMap.RegisterClassMap)).ToList()[1]; private static readonly MethodInfo RegisterClassMapWithoutExpressionMethod = typeof(BsonClassMap).GetMethods().First(x => x.Name == nameof(BsonClassMap.RegisterClassMap)); private static readonly MethodInfo MongoDBDataServiceFactorySetIsRootClassMethod = typeof(MongoDBDataServiceFactory).GetMethod(nameof(MongoDBDataServiceFactory.SetIsRootClass), BindingFlags.NonPublic | BindingFlags.Static);