public static MongoDefine GetDefinition() { if (_instance == null) { IEnumerable <Type> types = (from assembly in AppDomain.CurrentDomain.GetAssemblies() from assemblyType in assembly.GetTypes() where typeof(MongoDefine).IsAssignableFrom(assemblyType) && !assemblyType.IsAbstract select assemblyType).ToArray(); if (types.Count() == 0) { throw new Exception(string.Format("No types of {0} found, please declare one to define your database.", typeof(MongoDefine).Name)); } if (types.Count() > 1) { throw new Exception(string.Format("Multiple types of {0} found, only 1 type is allowed per application", typeof(MongoDefine).Name)); } _instance = Activator.CreateInstance(types.First()) as MongoDefine; } return(_instance); }
/// <summary> /// /// </summary> public void TruncateAllCollections() { MongoDefine instance = MongoTypeProvider.GetDefinition(); IEnumerable <MCollection> collections = instance.Define(); foreach (MCollection collection in collections) { if (_mongo.CollectionExists(collection.Name)) { _mongo.GetCollection(collection.Name).RemoveAll(); } } }
/// <summary> /// Initializes database. This is not fast, so avoid calling it constantly. Ideally, this method is called /// when your app starts up. /// </summary> public void InitializeDatabase() { MongoDefine instance = MongoTypeProvider.GetDefinition(); IEnumerable <MCollection> collections = instance.Define(); foreach (MCollection collection in collections) { if (!_mongo.CollectionExists(collection.Name)) { _mongo.CreateCollection(collection.Name); } // set up indexes if (collection.Indices.Length > 0) { _mongo.GetCollection <BsonDocument>(collection.Name).CreateIndex(IndexKeys.Ascending(collection.Indices), IndexOptions.SetUnique(true)); } } }