Ejemplo n.º 1
0
        private IMongoCollection <T> GetCollection <T>()
            where T : class
        {
            var mappingInfo = MongoDbMapper.GetMapping <T>();
            var collection  = MongoDbContext
                              .Database
                              .GetCollection <T>(mappingInfo.CollectionName);

            foreach (var item in mappingInfo.Indexes)
            {
                if (item.Properties.Count() > 1)
                {
                    var indexKeyDefintion = Builders <T> .IndexKeys.Ascending(item.Properties.First());

                    foreach (var prop in item.Properties.Skip(1))
                    {
                        indexKeyDefintion = indexKeyDefintion.Ascending(prop);
                    }
                    collection.Indexes.CreateOne(new CreateIndexModel <T>(indexKeyDefintion));
                }
                else
                {
                    collection.Indexes.CreateOne(
                        new CreateIndexModel <T>(
                            Builders <T> .IndexKeys.Ascending(item.Properties.First())));
                }
            }
            return(collection);
        }
Ejemplo n.º 2
0
        public static FilterDefinition <T> GetIdFilterFromIdValue <T>(this object idValue, Type entityType)
            where T : class
        {
            var mappingInfo   = MongoDbMapper.GetMapping(entityType);
            var filter        = FilterDefinition <T> .Empty;
            var filterBuilder = Builders <T> .Filter;

            if (entityType.IsInHierarchySubClassOf(typeof(PersistableEntity)))
            {
                filter = filterBuilder.Eq(nameof(PersistableEntity.Id), idValue);
            }
            else
            {
                if (entityType.IsInHierarchySubClassOf(typeof(ComposedKeyPersistableEntity)) ||
                    entityType.IsDefined(typeof(ComposedKeyAttribute)))
                {
                    var idValueProperties = idValue.GetType().GetAllProperties();
                    if (mappingInfo.IdProperties.Any(p => !idValueProperties.Any(pr => pr.Name == p)))
                    {
                        throw new InvalidOperationException("Provided id value is incomplete and cannot be used to search within database. " +
                                                            $"{entityType.Name}'s id required following fields : {string.Join(",", mappingInfo.IdProperties)}");
                    }
                    foreach (var item in idValueProperties)
                    {
                        filter &= filterBuilder.Eq(item.Name, item.GetValue(idValue));
                    }
                }
                else
                {
                    filter = filterBuilder.Eq(mappingInfo.IdProperty, idValue);
                }
            }

            return(filter);
        }
Ejemplo n.º 3
0
        public Startup(IHostingEnvironment env)
        {
            env.ConfigureNLog("nlog.config");
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            MongoDbMapper.RegisterAllMaps();
        }
Ejemplo n.º 4
0
        public async Task <T> GetByIdAsync <T>(object value) where T : class
        {
            var mappingInfo = MongoDbMapper.GetMapping <T>();

            if (string.IsNullOrWhiteSpace(mappingInfo.IdProperty) && mappingInfo.IdProperties?.Any() == false)
            {
                throw new InvalidOperationException($"The id field(s) for type {typeof(T).AssemblyQualifiedName} " +
                                                    $"has not been defined to allow searching by id." +
                                                    " You should either search with GetAsync method. You can also define id for this type by creating an 'Id' property (whatever type)" +
                                                    " or mark one property as id with the [PrimaryKey] attribute. Finally, you could define complex key with the [ComplexKey]" +
                                                    " attribute on top of your class to define multiple properties as part of the key.");
            }
            var collection = GetCollection <T>();
            var filter     = value.GetIdFilterFromIdValue <T>(typeof(T));
            var data       = await collection.FindAsync(filter).ConfigureAwait(false);

            return(data.FirstOrDefault());
        }
Ejemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            //.AddCustomSwagger()
            //.AddApplicationDI()
            .AddFluentValidation()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });

            ConfigureSwagger(services);

            services.Configure <DatabaseOptions>(Configuration.GetSection("Database"));

            services.AddCors(o => o.AddPolicy("DefaultPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("DefaultPolicy"));
            });

            services.AddLogging((logging) =>
            {
                logging.AddConsole();
                logging.AddEventSourceLogger();
            });

            Bootstraper.Configure(services);

            MongoDbMapper.MapClasses();
        }
Ejemplo n.º 6
0
        private object ExtractIdValue <T>(T entity)
            where T : class
        {
            var entityType  = entity.GetType();
            var mappingInfo = MongoDbMapper.GetMapping(entityType);

            if (string.IsNullOrWhiteSpace(mappingInfo.IdProperty) && mappingInfo.IdProperties?.Any() == false)
            {
                throw new InvalidOperationException($"The id field(s) for type {typeof(T).AssemblyQualifiedName} " +
                                                    $"has not been defined to allow update/delete object." +
                                                    " You should write data by yourself. You can also define id for this type by creating an 'Id' property (whatever type)" +
                                                    " or mark one property as id with the [PrimaryKey] attribute. Finally, you could define complex key with the [ComplexKey]" +
                                                    " attribute on top of your class to define multiple properties as part of the key.");
            }
            if (!string.IsNullOrWhiteSpace(mappingInfo.IdProperty))
            {
                return(entityType.GetAllProperties().First(p => p.Name == mappingInfo.IdProperty).GetValue(entity));
            }
            else
            {
                return(entityType.GetAllProperties().Where(p => mappingInfo.IdProperties.Contains(p.Name)).Select(p => p.GetValue(entity)).ToArray());
            }
        }
Ejemplo n.º 7
0
 private IMongoCollection <T> GetCollection <T>()
 => MongoDbContext.Database
 .GetCollection <T>(MongoDbMapper.GetMapping <T>().CollectionName);
 private IMongoCollection <T> GetCollection <T>()
 => MongoDbContext.MongoClient.GetDatabase(DatabaseName).GetCollection <T>(MongoDbMapper.GetMapping <T>().CollectionName);
Ejemplo n.º 9
0
 public MongoRepository()
 {
     _mappingInfo = MongoDbMapper.GetMapping <T>();
 }