Exemple #1
0
        public IEnumerable <User> GetByPredicate(Expression <Func <User, bool> > predicate, QueryParams <User> param)
        {
            try
            {
                //var currentPredicate = predicate.Convert<Entities.User, User>(mapper);
                var anotherPredicate = Mapper.Map <Expression <Func <User, bool> >, Expression <Func <Entities.User, bool> > >(predicate);
                param = QueryParams <User> .Validate(param, c => c.UserId, 10);

                using (Container = new ArticleContext())
                {
                    var list = Container.Users
                               .OrderBy(c => c.UserId)
                               .Where(anotherPredicate)
                               .Skip(param.Skip ?? 0)
                               .ToList();
                    var result = Mapper.Map <IEnumerable <Entities.User>, IEnumerable <User> >(list);
                    return(result.OrderBy(param.Order));
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #2
0
        public async Task <UserModel> RegisterAsync(RegistrationModel model)
        {
            var response = new UserModel();

            if (model == null)
            {
                response.Errors.Add(ErrorConstants.ModelIsNull);
                return(response);
            }

            var existingUser = await this.accountRepository.GetByEmailAsync(model.Email);

            if (existingUser != null)
            {
                response.Errors.Add(ErrorConstants.UserWithSameEmailExists);
                return(response);
            }

            var config = new MapperConfiguration(cfg => cfg.CreateMap <RegistrationModel, ApplicationUser>()
                                                 .ForMember("UserName", opt => opt.MapFrom(x => x.Login)));
            var mapper          = new AutoMapper.Mapper(config);
            var applicationUser = mapper.Map <RegistrationModel, ApplicationUser>(model);
            var result          = await this.userManager.CreateAsync(applicationUser, model.Password);

            if (!result)
            {
                response.Errors.Add(ErrorConstants.IncorrectInput);
                return(response);
            }

            await this.userManager.AddToRoleAsync(applicationUser);

            return(response);
        }
Exemple #3
0
        public async Task <UserModel> LogInAsync(LoginModel model, string password)
        {
            var response = new UserModel();

            if (model == null)
            {
                response.Errors.Add(ErrorConstants.ModelIsNull);
                return(response);
            }

            var existingUser = await this.accountRepository.GetByEmailAsync(model.Email);

            if (existingUser == null)
            {
                response.Errors.Add(ErrorConstants.IncorrectInput);
                return(response);
            }

            var result = await this.userManager.LogInAsync(existingUser, password);

            if (!result)
            {
                response.Errors.Add(ErrorConstants.IncorrectPassword);
                return(response);
            }

            var config = new MapperConfiguration(cfg => cfg.CreateMap <ApplicationUser, UserModel>()
                                                 .ForMember("Login", opt => opt.MapFrom(x => x.UserName)));
            var mapper = new AutoMapper.Mapper(config);

            response = mapper.Map <ApplicationUser, UserModel>(existingUser);
            return(response);
        }
Exemple #4
0
        public void AutomapperBenchmark()
        {
            var mapper = new AutoMapper.Mapper(new MapperConfiguration(config =>
                                                                       config.CreateMap <A, A>()));

            mapper.Map <A, A>(new A(), new A());
        }
Exemple #5
0
 public User Read(int id)
 {
     try
     {
         using (Container = new ArticleContext())
         {
             var user = Container.Users.FirstOrDefault(c => c.UserId == id);
             if (user != null)
             {
                 return(Mapper.Map <Entities.User, User>(user));
             }
             return(null);
         }
     }
     catch (DbEntityValidationException ex)
     {
         foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
         {
             foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
             {
                 Console.WriteLine(dbValidationError.ErrorMessage);
             }
         }
         throw ex;
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Exemple #6
0
        public ActionResult Save(Movie movie)
        {
            if (!ModelState.IsValid)
            {
                var viewModel = new MovieFormViewModel();

                var config = new MapperConfiguration(cfg => cfg.CreateMap <Movie, MovieFormViewModel>());
                var mapper = new AutoMapper.Mapper(config);
                mapper.Map(movie, viewModel);

                var genres = _context.Genres.ToList();
                viewModel.Genres = genres;

                return(View("MovieForm", viewModel));
            }

            if (movie.Id == 0)
            {
                movie.AddedDate = DateTime.Now;
                _context.Movies.Add(movie);
            }
            else
            {
                var moviesInDb = _context.Movies.Single(m => m.Id == movie.Id);

                var config = new MapperConfiguration(cfg => cfg.CreateMap <Movie, Movie>());
                var mapper = new AutoMapper.Mapper(config);
                mapper.Map(movie, moviesInDb);
            }

            _context.SaveChanges();

            return(RedirectToAction("Index", "Movies"));
        }
        public ActionResult Save(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                var viewModel = new CustomerFormViewModel
                {
                    Customer        = customer,
                    MembershipTypes = _context.MembershipTypes.ToList()
                };

                return(View("CustomerForm", viewModel));
            }

            if (customer.Id == 0)
            {
                _context.Customers.Add(customer);
            }
            else
            {
                var customerInDb = _context.Customers.Single(c => c.Id == customer.Id);

                var config = new MapperConfiguration(cfg => cfg.CreateMap <Customer, Customer>());
                var mapper = new AutoMapper.Mapper(config);
                mapper.Map(customer, customerInDb);
            }

            _context.SaveChanges();

            return(RedirectToAction("Index", "Customers"));
        }
Exemple #8
0
        /// <summary>
        ///  类型映射
        /// </summary>
        //public static T MapTo<T>(this object obj)
        //{
        //    var configuration = new AutoMapper.MapperConfiguration(cfg => cfg.AddMaps("Edoc2.Core"));
        //    var mapper = new AutoMapper.Mapper(configuration);

        //    return mapper.Map<T>(obj);
        //}

        /// <summary>
        ///  类型映射
        /// </summary>
        public static T MapTo <T>(this object obj)
        {
            if (obj == null)
            {
                return(default(T));
            }

            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap(obj.GetType(), typeof(T));

                var appServices = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.IsInterface == false && t.IsClass == true && t.CustomAttributes.Count() > 0 && t.Name.ToLower().EndsWith("dto"))).ToArray();
                foreach (var item in appServices)
                {
                    if (item.GetCustomAttributesData().Count() > 0 && item.GetCustomAttributesData()[0].AttributeType.Name == "AutoMapAttribute" && item.GetCustomAttributesData()[0].ConstructorArguments.Count() > 0)
                    {
                        Type target = (Type)item.GetCustomAttributesData()[0].ConstructorArguments[0].Value;
                        cfg.CreateMap(target, item);
                    }
                }
            });
            var mapper = new AutoMapper.Mapper(configuration);

            return(mapper.Map <T>(obj));
        }
Exemple #9
0
        public async Task <ActionResult> GetClientCheckups(long customerid)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }

                var lst = await _dBRepository.client_periodic_checkups.Where(l => l.account_id == customerid && l.is_deleted == false).AsNoTracking().ToListAsync();

                var result = new List <ClientPeriodicCheckupModel>();

                var mapper = new AutoMapper.Mapper(new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap <ClientPeriodicCheckUp, ClientPeriodicCheckupModel>();
                }));
                mapper.Map(lst, result);

                return(Ok(new CoreResponse()
                {
                    is_success = true, data = result
                }));
            }
            catch (Exception ex)
            {
                return(Ok(new CoreResponse()
                {
                    is_success = false, data = null, dev_message = ex.Message
                }));
            }
        }
        public static Output Convert <Input, Output>(Input item)
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap <Input, Output>());
            var mapper = new AutoMapper.Mapper(config);

            return(mapper.Map <Output>(item));
        }
Exemple #11
0
        public IEnumerable <User> GetAll(QueryParams <User> param)
        {
            try
            {
                param = QueryParams <User> .Validate(param, c => c.UserId, 10);

                using (Container = new ArticleContext())
                {
                    var list   = Container.Users.OrderBy(c => c.UserId).Skip(param.Skip ?? 0).Take(param.Take ?? 0).ToList();
                    var result = Mapper.Map <IEnumerable <Entities.User>, IEnumerable <User> >(list);
                    return(result.OrderBy(param.Order));
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw ex;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #12
0
        public Tdestination Map <Tdestination, TSource>(TSource model)
        {
            var config = new MapperConfiguration(config => config.CreateMap(typeof(TSource), typeof(Tdestination)));
            var mapper = new AutoMapper.Mapper(config);

            return(mapper.Map <Tdestination>(model));
        }
        public List <DgvDetalleNota> MapDgvVentas(List <DetalleNotaEntity> origen)
        {
            var mapper  = new AutoMapper.Mapper(datagridVentasConfig);
            var dgvList = mapper.Map <List <DetalleNotaEntity>, List <DgvDetalleNota> >(origen);

            dgvList.ForEach(x => x.Total = x.Cantidad * x.PrecioVenta);
            return(dgvList);
        }
        public static TDestiantion Map <TSource, TDestiantion>(TSource source)
            where TSource : class
            where TDestiantion : class
        {
            var configuration = new MapperConfiguration(cfg => cfg.CreateMap <TSource, TDestiantion>());
            var mapper        = new AutoMapper.Mapper(configuration);

            return(mapper.Map <TDestiantion>(source));
        }
Exemple #15
0
        public async Task <List <CountryViewModel> > GetList()
        {
            var response = await _client.GetAsync("https://api.covid19api.com/summary");

            var content = _mapper.Map <ApiModel>(response.Content);
            List <Countries>        countries = content.Countries;
            List <CountryViewModel> result    = (List <CountryViewModel>)countries.Select(x => new CountryViewModel(x.TotalConfirmed - x.TotalRecovered, x.Country)).ToList().OrderBy(X => X.ActiveCases).Take(10);

            return(result);
        }
Exemple #16
0
        // GET api/movies/5
        public IHttpActionResult GetMovie(int id)
        {
            var movie = _context.Movies.SingleOrDefault(m => m.Id == id);

            if (movie == null)
            {
                return(NotFound());
            }

            var movieDto = Mapper.Map <Movie, MovieDto>(movie);

            return(Ok(movieDto));
        }
        /// <summary>
        /// 映射
        /// </summary>
        /// <typeparam name="TSource">源实例类型</typeparam>
        /// <typeparam name="TTarget">目标实例类型</typeparam>
        /// <param name="sourceInstance">源实例</param>
        /// <param name="beforeMapEventHandler">映射前事件处理者</param>
        /// <param name="afterMapEventHandler">映射后事件处理者</param>
        /// <param name="ignoreMembers">忽略映射成员集</param>
        /// <returns>目标实例</returns>
        public static TTarget Map <TSource, TTarget>(this TSource sourceInstance, Action <TSource, TTarget> beforeMapEventHandler = null, Action <TSource, TTarget> afterMapEventHandler = null, params Expression <Func <TTarget, object> >[] ignoreMembers)
        {
            #region # 验证

            if (sourceInstance == null)
            {
                return(default(TTarget));
            }

            #endregion

            lock (_Sync)
            {
                string key = $"{typeof(TSource).FullName},{typeof(TTarget).FullName}";
                if (!_MapperConfigurations.TryGetValue(key, out MapperConfiguration mapperConfiguration))
                {
                    MapperConfigurationExpression         configExpression  = new MapperConfigurationExpression();
                    IMappingExpression <TSource, TTarget> mappingExpression = configExpression.CreateMap <TSource, TTarget>();

                    #region # 忽略映射成员处理

                    foreach (Expression <Func <TTarget, object> > ignoreMember in ignoreMembers)
                    {
                        mappingExpression.ForMember(ignoreMember, source => source.Ignore());
                    }

                    #endregion

                    #region # 映射前后事件处理

                    if (beforeMapEventHandler != null)
                    {
                        mappingExpression.BeforeMap(beforeMapEventHandler);
                    }
                    if (afterMapEventHandler != null)
                    {
                        mappingExpression.AfterMap(afterMapEventHandler);
                    }

                    #endregion

                    mapperConfiguration = new MapperConfiguration(configExpression);
                    _MapperConfigurations.Add(key, mapperConfiguration);
                }

                IMapper mapper = new AutoMapper.Mapper(mapperConfiguration);
                return(mapper.Map <TTarget>(sourceInstance));
            }
        }
Exemple #18
0
        public async Task <UserModel> GetUserByIdAsync(long id)
        {
            var response     = new UserModel();
            var existingUser = await this.accountRepository.GetByIdAsync(id);

            if (existingUser == null)
            {
                response.Errors.Add(ErrorConstants.ImpossibleToFindUser);
                return(response);
            }

            var config = new MapperConfiguration(cfg => cfg.CreateMap <ApplicationUser, UserModel>()
                                                 .ForMember("Login", opt => opt.MapFrom(x => x.UserName)));
            var mapper = new AutoMapper.Mapper(config);

            response = mapper.Map <ApplicationUser, UserModel>(existingUser);
            return(response);
        }
Exemple #19
0
        public IHttpActionResult UpdateMovie(int id, MovieDto movieDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var movieInDb = _context.Movies.SingleOrDefault(m => m.Id == id);

            if (movieInDb == null)
            {
                return(NotFound());
            }

            Mapper.Map(movieDto, movieInDb);

            _context.SaveChanges();

            return(Ok());
        }
Exemple #20
0
        public ActionResult Edit(int id)
        {
            var movie = _context.Movies.Include(m => m.Genres).ToList().SingleOrDefault(m => m.Id == id);

            if (movie == null)
            {
                return(new HttpNotFoundResult());
            }

            var viewModel = new MovieFormViewModel();

            var config = new MapperConfiguration(cfg => cfg.CreateMap <Movie, MovieFormViewModel>());
            var mapper = new AutoMapper.Mapper(config);

            mapper.Map(movie, viewModel);

            var genres = _context.Genres.ToList();

            viewModel.Genres = genres;

            return(View("MovieForm", viewModel));
        }
Exemple #21
0
        public int Save(User entity, bool now = true)
        {
            try
            {
                if (entity == null)
                {
                    return(-1);
                }
                using (Container = new ArticleContext())
                {
                    var artDb = Mapper.Map <User, Entities.User>(entity);

                    Container.Users.Add(artDb);
                    if (now)
                    {
                        Container.SaveChanges();
                    }
                    entity.UserId = artDb.UserId;

                    return(artDb.UserId);
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var dbEntityValidationResult in ex.EntityValidationErrors)
                {
                    foreach (var dbValidationError in dbEntityValidationResult.ValidationErrors)
                    {
                        Console.WriteLine(dbValidationError.ErrorMessage);
                    }
                }
                throw;
            }
            catch (Exception e)
            {
                throw;
            }
        }
Exemple #22
0
        /// <summary>
        /// 集合列表类型映射
        /// </summary>
        public static List <TDestination> MapToList <TDestination>(this IEnumerable source)
        {
            //为空
            if (source == null || source.GetEnumerator().MoveNext() == false)
            {
                return(default(List <TDestination>));
            }



            Type type = null;

            foreach (var first in source)
            {
                type = first.GetType();
                break;
            }
            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap(type, typeof(TDestination));
                //cfg.CreateMap(typeof(Roles.Role), typeof(Roles.RoleDto));
                //cfg.CreateMap(typeof(Permissions.Permission), typeof(PermissionDto));

                var appServices = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.IsInterface == false && t.IsClass == true && t.CustomAttributes.Count() > 0 && t.Name.ToLower().EndsWith("dto"))).ToArray();
                foreach (var item in appServices)
                {
                    if (item.GetCustomAttributesData().Count() > 0 && item.GetCustomAttributesData()[0].AttributeType.Name == "AutoMapAttribute" && item.GetCustomAttributesData()[0].ConstructorArguments.Count() > 0)
                    {
                        Type target = (Type)item.GetCustomAttributesData()[0].ConstructorArguments[0].Value;
                        cfg.CreateMap(target, item);
                    }
                }
            });
            var mapper = new AutoMapper.Mapper(configuration);

            return(mapper.Map <List <TDestination> >(source));
        }
Exemple #23
0
        public IHttpActionResult CreateMovie(MovieDto movieDto)
        {
            if (!ModelState.IsValid)
            {
                var modelErrors = "";
                foreach (var modelState in ModelState.Values)
                {
                    foreach (var modelError in modelState.Errors)
                    {
                        modelErrors = modelErrors + modelError.ErrorMessage;
                    }
                }
                return(BadRequest("Model not valid: " + modelErrors));
            }

            var movie = Mapper.Map <MovieDto, Movie>(movieDto);

            _context.Movies.Add(movie);
            _context.SaveChanges();

            movieDto.Id = movie.Id;

            return(Created(new Uri(Request.RequestUri + "/" + movieDto.Id), movieDto));
        }
Exemple #24
0
 public Customer AutoMapperBenchmark() => _autoMapper.Map <CustomerDto, Customer>(_dto);
Exemple #25
0
        //método para mapear de una lista de objetos del modelo a uno del controlador.
        public List <UsuariosData> MapList(List <UsuarioEntity> origenList)
        {
            var mapper = new AutoMapper.Mapper(config);

            return(mapper.Map <List <UsuarioEntity>, List <UsuariosData> >(origenList));
        }
Exemple #26
0
        //método para mapear de un objeto del modelo a uno del controlador.
        public UsuariosData Map(UsuarioEntity origen)
        {
            var mapper = new AutoMapper.Mapper(config);

            return(mapper.Map <UsuarioEntity, UsuariosData>(origen));
        }
Exemple #27
0
 public static TransactionModel ToServiceModel(this TransactionViewModel model)
 {
     return(Mapper.Map <TransactionViewModel, TransactionModel>(model));
 }
Exemple #28
0
 public static LeaseModel ToServiceModel(this LeaseCreateViewModel model)
 {
     return(Mapper.Map <LeaseCreateViewModel, LeaseModel>(model));
 }
Exemple #29
0
 public static LeaseViewModel ToViewModel(this LeaseModel model)
 {
     return(Mapper.Map <LeaseModel, LeaseViewModel>(model));
 }
Exemple #30
0
 public static LeaseApplicationViewModel ToViewModel(this LeaseApplicationModel model)
 {
     return(Mapper.Map <LeaseApplicationModel, LeaseApplicationViewModel>(model));
 }