Beispiel #1
0
        public async Task RunSeeder <T>(List <T> data)
        {
            Type t = typeof(T);

            DBConfig.CollectionAttribute collection = t.GetCustomAttributes(true).FirstOrDefault(c => c.GetType() == typeof(DBConfig.CollectionAttribute)) as DBConfig.CollectionAttribute;
            var collections = await db.ListCollectionsAsync(new ListCollectionsOptions
            {
                Filter = new BsonDocument("name", collection.collectionName)
            });

            if (!await collections.AnyAsync())
            {
                await db.CreateCollectionAsync(collection.collectionName);

                var result = db.GetCollection <T>(collection.collectionName);
                if (collection.indexes.Length > 0)
                {
                    var indexDefinition = Builders <T> .IndexKeys.Combine(collection.indexes.Select(c => Builders <T> .IndexKeys.Ascending(c)));

                    string s = await result.Indexes.CreateOneAsync(indexDefinition);
                }
                await result.InsertManyAsync(data);
            }
            else
            {
                var result = db.GetCollection <T>(collection.collectionName);
                await result.InsertManyAsync(data);
            }
        }
Beispiel #2
0
        public IMongoCollection <T> getCollection <T>()
        {
            Type t = typeof(T);

            DBConfig.CollectionAttribute collection = t.GetCustomAttributes(true).FirstOrDefault(c => c.GetType() == typeof(DBConfig.CollectionAttribute)) as DBConfig.CollectionAttribute;

            if (collection == null)
            {
                throw new Exception("Cannot find the collection from entity model");
            }
            return(createCollection <T>(collection.collectionName, collection.indexes).Result);
        }