Beispiel #1
0
        private static object GetCollecion(IMongoDatabase db, Type type)
        {
            CollectionOptionsAttribute attr = (CollectionOptionsAttribute)Attribute.GetCustomAttribute(type, typeof(CollectionOptionsAttribute), inherit: false);

            if (attr != null && attr.Ignore || type.IsAbstract)
            {
                return(null);
            }
            string collectionName = attr?.Name ?? type.Name;

            if (attr != null && !CheckCollectionExists(db, collectionName))
            {
                CreateCollectionOptions options = new CreateCollectionOptions();
                if (attr.Capped)
                {
                    options.Capped = attr.Capped;
                    if (attr.MaxSize > 0)
                    {
                        options.MaxSize = attr.MaxSize;
                    }
                    if (attr.MaxDocuments > 0)
                    {
                        options.MaxDocuments = attr.MaxDocuments;
                    }
                }
                db.CreateCollection(collectionName, options);
            }

            var getCollectionMethod = typeof(IMongoDatabase).GetMethod(nameof(IMongoDatabase.GetCollection));
            var genericMethod       = getCollectionMethod.MakeGenericMethod(type);

            return(genericMethod.Invoke(db, new object[] { collectionName, null }));
        }
Beispiel #2
0
        private static IMongoCollection <T> GetCollection <T>(IMongoDatabase db)
        {
            CollectionOptionsAttribute attr = (CollectionOptionsAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(CollectionOptionsAttribute));
            string collectionName           = attr?.Name ?? typeof(T).Name;

            if (attr != null && !CheckCollectionExists(db, collectionName))
            {
                CreateCollectionOptions options = new CreateCollectionOptions();
                if (attr.Capped)
                {
                    options.Capped = attr.Capped;
                    if (attr.MaxSize > 0)
                    {
                        options.MaxSize = attr.MaxSize;
                    }
                    if (attr.MaxDocuments > 0)
                    {
                        options.MaxDocuments = attr.MaxDocuments;
                    }
                }
                db.CreateCollection(collectionName, options);
            }
            return(db.GetCollection <T>(collectionName));
        }