public void multiple_inherited_base_mappings_of_same_type_fails()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<MyClass, MyDto>()
                    .ForMember(d => d.Information, m => m.MapFrom(s => s.CurrentInformation))
                    .Include<MySpecificClass, MySpecificDto>();
                cfg.CreateMap<MySpecificClass, MySpecificDto>();

                cfg.CreateMap<InformationClass, InformationDto>();
            });

            config.AssertConfigurationIsValid();
        }
예제 #2
0
        /// <summary>
        /// 取得所有客戶資料
        /// </summary>
        /// <returns></returns>
        public List<CustomerViewModel> Get()
        {
            #region 很累的寫法(一個一個丟)
            //List<CustomerViewModel> model = new List<CustomerViewModel>();
            //var DbResult = db.Get().AsQueryable();
            //
            //foreach (var item in DbResult)
            //{
            //    //將Customers的清單資料一個一個丟到CustomerViewModel
            //    CustomerViewModel _model = new CustomerViewModel();
            //    _model.CustomerID = item.CustomerID;
            //    _model.ContactName = item.ContactName;
            //    model.Add(_model);
            //}
            //
            //return model.AsQueryable();
            #endregion

            #region 改用AutoMapper
            var DbResult = db.Get().ToList();
            //AntoMapper before V4.2
            //Mapper.CreateMap<Customers, CustomerViewModel>();
            //
            //return Mapper.Map<List<Customers>, List<CustomerViewModel>>(DbResult);

            var config = new MapperConfiguration(cfg => cfg.CreateMap<Customers, CustomerViewModel>());
            config.AssertConfigurationIsValid();//驗證應對

            var mapper = config.CreateMapper();
            return mapper.Map<List<Customers>, List<CustomerViewModel>>(DbResult);
            #endregion
        }
예제 #3
0
        public void Example()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<ContainsASrc, ContainsADest>();

                cfg.CreateMap<ASrc, ADest>()
                    .Include<BSrc, BDest>()
                    .Include<CSrc, CDest>();

                cfg.CreateMap<BSrc, BDest>()
                    .Include<CSrc, CDest>();

                cfg.CreateMap<CSrc, CDest>();
            });

            var expectedCSrc = new CSrc() {StringA = "A", StringB = "B", StringC = "C"};
            var expectedBSrc = new BSrc() {StringA = "A", StringB = "B"};

            var expectedContCSrc = new ContainsASrc() {A = expectedCSrc};
            var expectedContBSrc = new ContainsASrc() {A = expectedBSrc};

            var mapper = config.CreateMapper();
            var actualContCDest = mapper.Map<ContainsASrc, ContainsADest>(expectedContCSrc);
            var actualContBDest = mapper.Map<ContainsASrc, ContainsADest>(expectedContBSrc); // THROWS

            config.AssertConfigurationIsValid();
            actualContBDest.ShouldNotBeNull();
            actualContCDest.ShouldNotBeNull();
        }
예제 #4
0
 public void AutoMapper_DomainToDataMappingTest()
 {
     var config = new MapperConfiguration(cfg => {
         DomainToDataMapping.CreateMaps(cfg);
     });
     config.AssertConfigurationIsValid();
 }
예제 #5
0
        // <summary>取得所有客戶資料(分頁)</summary>
        /// <returns></returns>
        public IQueryable<CustomerViewModel> Get(int CurrPage, int PageSize, out int TotalRow)
        {
            // 取得所有筆數
            TotalRow = db.Get().ToList().Count();

            // 使用Linq篩選分頁
            var DbResult = db.Get().ToList().Skip((CurrPage - 1) * PageSize).Take(PageSize).ToList();

            #region AutoMapper V4.2 以前的寫法
            // Mapping到ViewModel
            
            //
            //Mapper.CreateMap<Customers, CustomerViewModel>();
            //return Mapper.Map<List<Customers>, List<CustomerViewModel>>(DbResult).AsQueryable();
            #endregion

            #region 新版AutoMapper 寫法
            //AutoMapper V >= 4.2 的寫法
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Customers, CustomerViewModel>());
            config.AssertConfigurationIsValid();//驗證應對

            var mapper = config.CreateMapper();
            return mapper.Map<List<Customers>, List<CustomerViewModel>>(DbResult).AsQueryable();
            #endregion
        }
예제 #6
0
            public void Should_map_the_existing_array_elements_over()
            {
                var sourceList = new List<SourceObject>();
                var destList = new List<DestObject>();

                var config = new MapperConfiguration(cfg => cfg.CreateMap<SourceObject, DestObject>().PreserveReferences());
                config.AssertConfigurationIsValid();

                var source1 = new SourceObject
                {
                    Id = 1,
                };
                sourceList.Add(source1);

                var source2 = new SourceObject
                {
                    Id = 2,
                };
                sourceList.Add(source2);

                source1.AddChild(source2); // This causes the problem

                config.CreateMapper().Map(sourceList, destList);

                destList.Count.ShouldEqual(2);
                destList[0].Children.Count.ShouldEqual(1);
                destList[0].Children[0].ShouldBeSameAs(destList[1]);
            }
        public static void Initialize()
        {
            MapperConfig = new MapperConfiguration(mapper =>
            {
                mapper.CreateMap<ParentTouristSite, FullTouristSiteResponseModel>()
                    .ForMember(
                        m => m.Type,
                        opts => opts.MapFrom(p => (int)p.Type)); ;

                mapper.CreateMap<TouristSite, TouristSiteResponseModel>()
                    .ForMember(
                        m => m.Rating,
                        opts => opts.MapFrom(t => t.Ratings.Count > 0 ? t.Ratings.Sum(r => r.Value) / t.Ratings.Count : 0))
                    .ForMember(
                        m => m.Status,
                        opts => opts.MapFrom(t => (int)t.Status));

                mapper.CreateMap<TouristSite, SimpleTouristSiteResponseModel>();

                mapper.CreateMap<ParentTouristSite, SimpleParentTouristSiteResponseModel>();

                mapper.CreateMap<User, ScoreboardResponseModel>().ForMember(
                        m => m.Rating,
                        opts => opts.MapFrom(u => u.CalculatedRating));

                mapper.CreateMap<User, FullUserResponseModel>();

                mapper.CreateMap<Badge, BadgeResponseModel>().ForMember(
                        m => m.Title,
                        opts => opts.MapFrom(b => Enum.GetName(typeof(BadgeTitle), b.Title)));
            });

            MapperConfig.AssertConfigurationIsValid();
        }
예제 #8
0
        private void ConfigureMapper()
        {
            //var config = Mapper.Configuration;
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Record, JWSModels.Record>().ForMember(target => target.TierLevel, opts => opts.Ignore()).ForMember(target => target.TierLevelId, opts => opts.Ignore()).ForMember(target => target.TierName, opts => opts.Ignore()).ForMember(target => target.UserLevel, opts => opts.Ignore()).ForMember(target => target.IndexCode, opts => opts.Ignore()).ForMember(target => target.NumberPayPeriods, opts => opts.Ignore()).ForMember(target => target.PayRatePerPayPeriod, opts => opts.Ignore()).ForMember(target => target.AnnualHours, opts => opts.Ignore()).ForMember(target => target.AnnualPayRate, opts => opts.Ignore()).ForMember(target => target.AddressLine1, opts => opts.ResolveUsing(c => c.Address1)).ForMember(target => target.AddressLine2, opts => opts.ResolveUsing(c => c.Address2)).ForMember(target => target.City, opts => opts.ResolveUsing(c => c.City)).ForMember(target => target.DateOfBirth, opts => opts.ResolveUsing(c => c.DateOfBirth)).ForMember(target => target.DaysWorkedPerWeek, opts => opts.Ignore()).ForMember(target => target.EmployeeId, opts => opts.Ignore()).ForMember(target => target.FirstName, opts => opts.ResolveUsing(c => c.FirstName)).ForMember(target => target.Gender, opts => opts.ResolveUsing(c => c.Gender)).ForMember(target => target.HireDate, opts => opts.ResolveUsing(c => c.HireDate)).ForMember(target => target.JobClassCode, opts => opts.Ignore()).ForMember(target => target.JobDescription, opts => opts.Ignore()).ForMember(target => target.LastName, opts => opts.ResolveUsing(c => c.LastName)).ForMember(target => target.OccupationCode, opts => opts.Ignore()).ForMember(target => target.PayRate, opts => opts.Ignore()).ForMember(target => target.HoursWorkedPerDay, opts => opts.Ignore()).ForMember(target => target.PayRateType, opts => opts.Ignore()).ForMember(target => target.PhoneNumber, opts => opts.Ignore()).ForMember(target => target.SocialSecurityNumber, opts => opts.ResolveUsing(c => c.SocialSecurityNumber)).ForMember(target => target.State, opts => opts.ResolveUsing(c => c.State)).ForMember(target => target.UnionCode, opts => opts.Ignore()).ForMember(target => target.NameSuffix, opts => opts.Ignore()).ForMember(target => target.ZipCode, opts => opts.ResolveUsing(c => c.ZipCode)).AfterMap((src, target) =>
                {
                    TierMapping tierMapping; //= new TierMapping(this, target);

                    if (!src.DepartmentName.IsEmpty())
                    {
                        tierMapping = new TierMapping(this, target, src.DepartmentName);
                        tierMapping.MapOrgLevel(Tiers4, 4, src.DepartmentName.ToUpper(), src.DepartmentName.ToUpper(), MissingOrganizationMappingEncountered, MultipleOrganizationMappingEncountered);
                    }

                    if (!src.DivisionName.IsEmpty())
                    {
                        tierMapping = new TierMapping(this, target, src.DivisionName);
                        tierMapping.MapOrgLevel(Tiers3, 3, src.DivisionName.ToUpper(), src.DivisionName.ToUpper(), MissingOrganizationMappingEncountered, MultipleOrganizationMappingEncountered);
                    }
                });
            });
            config.AssertConfigurationIsValid();
            mapper = config.CreateMapper();
        }
예제 #9
0
            public void ExampleIgnoring()
            {
                var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Source, Destination>().ForMember(m => m.SomeValuefff, opt => opt.Ignore())
                    );

                config.AssertConfigurationIsValid();
            }
예제 #10
0
 public void Configure(IEnumerable<IAutoMapperTypeConfigurator> autoMapperTypeConfigurators)
 {
     var mapperConfiguration = new MapperConfiguration(cfg =>
     {
         autoMapperTypeConfigurators.ToList().ForEach(x => x.Configure(cfg));
     });
     mapperConfiguration.AssertConfigurationIsValid();
 }
        public static IMapper Configure()
        {
            var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<Album, HomeIndexAlbumViewModel>();
            });

            config.AssertConfigurationIsValid();

            return config.CreateMapper();
        }
 public OpportunityRepository()
 {
     config = new MapperConfiguration(cfg =>
     {
         cfg.CreateMap<Opportunity, OpportunityDocument>();
         cfg.CreateMap<OpportunityDocument, Opportunity>();
     });
     config.AssertConfigurationIsValid();
     mapper = config.CreateMapper();
 }
        public void Should_map_enum_to_nullable()
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap<DummySource, DummyDestination>());
            config.AssertConfigurationIsValid();
            DummySource src = new DummySource() { Dummy = DummyTypes.Bar };

            var destination = config.CreateMapper().Map<DummySource, DummyDestination>(src);

            destination.Dummy.ShouldEqual((int)DummyTypes.Bar);
        }
예제 #14
0
        private void ConfigureMapper()
        {

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Record, JWSModels.Record>()
                    .ForMember(target => target.TierLevel, opts => opts.Ignore())
                    .ForMember(target => target.TierLevelId, opts => opts.Ignore())
                    .ForMember(target => target.TierName, opts => opts.Ignore())
                    .ForMember(target => target.UserLevel, opts => opts.Ignore())
                    .ForMember(target => target.IndexCode, opts => opts.Ignore())
                    .ForMember(target => target.NumberPayPeriods, opts => opts.Ignore())
                    .ForMember(target => target.PayRatePerPayPeriod, opts => opts.Ignore())
                    .ForMember(target => target.AnnualHours, opts => opts.Ignore())
                    .ForMember(target => target.AnnualPayRate, opts => opts.Ignore())
                    .ForMember(target => target.NameSuffix, opts => opts.Ignore())
                    .ForMember(target => target.OccupationCode, opts => opts.Ignore())
                    .ForMember(target => target.UnionCode, opts => opts.Ignore())
                    .ForMember(target => target.PhoneNumber, opts => opts.Ignore())
                    .ForMember(target => target.JobDescription, opts => opts.Ignore())
                    .ForMember(target => target.AddressLine1, opts => opts.ResolveUsing(c => c.Address1))
                    .ForMember(target => target.AddressLine2, opts => opts.ResolveUsing(c => c.Address2))
                    .ForMember(target => target.EmployeeId, opts => opts.ResolveUsing(c => c.EmployeeId))
                    .ForMember(target => target.HoursWorkedPerDay, opts => opts.ResolveUsing(c => c.HoursWorkedPerDay))
                    .ForMember(target => target.DaysWorkedPerWeek, opts => opts.ResolveUsing(c => c.DaysWorkedPerWeek))
                    .ForMember(target => target.JobClassCode, opts => opts.ResolveUsing(c => c.JobClassCode))
                       .AfterMap((src, target) =>
                       {


                           TierMapping tierMapping;//= new TierMapping(this, target);
                           if (src.DivisionNumber > 0)
                           {
                               tierMapping = new TierMapping(this, target, src.DivisionNumber.ToString());
                               //var list = OrgList.Where(c => c.Number.Contains(src.DivisionNumber.ToString()));

                               tierMapping.MapOrgLevel(Tiers3, 3, src.DivisionNumber.ToString(), string.Empty,
                                   MissingOrganizationMappingEncountered, MultipleOrganizationMappingEncountered);

                           }


                       });





            });


            config.AssertConfigurationIsValid();


        }
예제 #15
0
        private void ConfigureMapper()
        {
            var config = new MapperConfiguration(cfg =>
           {


                cfg.CreateMap<Record, JWSModels.Record>()
                .ForMember(target => target.DaysWorkedPerWeek, opts => opts.Ignore())
                .ForMember(target => target.OccupationCode, opts => opts.Ignore())
                .ForMember(target => target.UnionCode, opts => opts.Ignore())
                .ForMember(target => target.NumberPayPeriods, opts => opts.Ignore())
                .ForMember(target => target.AnnualHours, opts => opts.Ignore())
                .ForMember(target => target.AnnualPayRate, opts => opts.Ignore())
                .ForMember(target => target.TierLevel, opts => opts.Ignore())
                .ForMember(target => target.TierLevelId, opts => opts.Ignore())
                .ForMember(target => target.TierName, opts => opts.Ignore())
                .ForMember(target => target.UserLevel, opts => opts.Ignore())
                .ForMember(target => target.IndexCode, opts => opts.Ignore())
                .ForMember(target => target.AddressLine1, opts => opts.ResolveUsing(c => c.Address1))
                .ForMember(target => target.AddressLine2, opts => opts.ResolveUsing(c => c.Address2))
                .ForMember(target => target.PayRatePerPayPeriod, opts => opts.ResolveUsing(c => c.PayRate))
                .AfterMap((src, target) =>
                {


                    var tierMapping = new TierMapping(this, target);
                    if (!src.Level5Name.IsEmpty())
                    {
                        tierMapping.MapOrgLevel(Tiers5, 5, src.Level5Name.ToUpper(), src.DepartmentName.ToUpper(),
                            MissingOrganizationMappingEncountered, MultipleOrganizationMappingEncountered);
                    }
                    if (!src.DepartmentName.IsEmpty())
                    {
                        tierMapping = new TierMapping(this, target, src.DepartmentNumber);
                        tierMapping.MapOrgLevel(Tiers4, 4, src.DepartmentName.ToUpper(), src.DivisionName.ToUpper(),
                            MissingOrganizationMappingEncountered, MultipleOrganizationMappingEncountered);
                    }
                    if (target.TierLevel == 0)
                    {
                        target.TierLevel = 2;
                        target.TierLevelId = "109".PadLeft(6, '0');

                    }




                });


            });
            config.AssertConfigurationIsValid();
            mapper = config.CreateMapper();

        }
예제 #16
0
        public void GlobalIgnore_ignores_properties_with_names_matching_but_different_types()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddGlobalIgnore("ShouldBeMapped");
                cfg.CreateMap<Source, DestinationWrongType>();
            });

            config.CreateMapper().Map<Source, DestinationWrongType>(new Source { ShouldBeMapped = "true" });
            config.AssertConfigurationIsValid();
        }
 public void included_mapping_should_inherit_base_mappings_should_not_throw()
 {
     var config = new MapperConfiguration(cfg =>
     {
         cfg.CreateMap<ModelObject, DtoObject>()
             .ForMember(d => d.BaseString, m => m.MapFrom(s => s.DifferentBaseString))
             .Include<ModelSubObject, DtoSubObject>();
         cfg.CreateMap<ModelSubObject, DtoSubObject>();
     });
     config.AssertConfigurationIsValid();
 }
예제 #18
0
 public void GlobalIgnore_ignores_all_properties_beginning_with_string()
 {
     var config = new MapperConfiguration(cfg =>
     {
         cfg.AddGlobalIgnore("StartingWith");
         cfg.CreateMap<Source, Destination>()
             .ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore());
     });
     
     config.CreateMapper().Map<Source, Destination>(new Source{ShouldBeMapped = "true"});
     config.AssertConfigurationIsValid();
 }
        //private IMapper reverseMapper;
        public CrimeTypeService()
        {
            _unitOfWork = new UnitOfWork();

            //config mapper
            var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<CrimeType, CrimeTypeEntity>();
            });
            config.AssertConfigurationIsValid();
            //create mapper
            mapper = config.CreateMapper();
        }
 private static void InitialAutomapper()
 {
     if(mapper == null)
     {
         lock(mapperSyncRoot)
         {
             MapperConfiguration configuration = new MapperConfiguration(MapperConfigure);
             configuration.AssertConfigurationIsValid();
             mapper = configuration.CreateMapper();
         }
     }
 }
 public void more_specific_map_should_override_base_ignore_passes_validation()
 {
     var config = new MapperConfiguration(cfg =>
     {
         cfg.CreateMap<ModelObject, DtoObject>()
             .ForMember(d => d.BaseString, m => m.Ignore())
             .Include<ModelSubObject, DtoSubObject>();
         cfg.CreateMap<ModelSubObject, DtoSubObject>()
             .ForMember(d => d.BaseString, m => m.MapFrom(s => s.DifferentBaseString));
     });
     config.AssertConfigurationIsValid();
 }
        public void inhertited_ignore_should_be_pass_validation()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<BaseDomain, Dto>()
                    .ForMember(d => d.SpecificProperty, m => m.Ignore())
                    .Include<SpecificDomain, Dto>();

                cfg.CreateMap<SpecificDomain, Dto>();
            });

            config.AssertConfigurationIsValid();
        }
예제 #23
0
파일: CNCUnitTest.cs 프로젝트: aiten/CNCLib
		protected override void InitializeCoreDependencies()
		{
			var config = new MapperConfiguration(cfg =>
			{
				cfg.AddProfile<LogicAutoMapperProfile>();
				cfg.AddProfile<WpfAutoMapperProfile>();
			});
			config.AssertConfigurationIsValid();

			var mapper = config.CreateMapper();

			Dependency.Container.RegisterInstance<IMapper>(mapper);
		}
예제 #24
0
        /// <summary>
        /// Creates the mapper configuration.
        /// </summary>
        /// <returns>The mapper configuration.</returns>
        public static MapperConfiguration CreateConfiguration()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Employee, EmployeeDto>()
                    .ForMember(dst => dst.Date, opt => opt.ResolveUsing(src =>
                    {
                        return src.Date.HasValue ? src.Date.Value.ToShortDateString() : string.Empty;
                    }));
            });

            config.AssertConfigurationIsValid();

            return config;
        }
예제 #25
0
        /// <summary>
        /// Custom value resolvers : https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers
        /// 建立Resolver處理映射到目的物件時, 將來源物件做處理後再映射到目的物件.
        /// 這個範例是將來源物件的FirstName+LastName後, 映射到目的物件的Name
        /// </summary>
        private static void ValueResolverTest()
        {
            var customer = new Customer() { FirstName = "Tony", LastName = "Chen", Address = "Taipei", Age = 30 };
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Customer, CustomerView>()
                .ForMember(dest => dest.Name, opt => opt.ResolveUsing<CustomerView>()));
            var mapper = config.CreateMapper();

            //驗證: 如果0個field被mapping到目的地, 就會發生assert
            config.AssertConfigurationIsValid();

            var destination = mapper.Map<CustomerView>(customer);
            Console.WriteLine("------------------\nResolver處理映射到目的物件範例:\n---------------\n");
            Console.WriteLine("來源:CustomerView內容:{0}", customer.Dump());
            Console.WriteLine("目的:CustomerView內容(經過resolver):{0}", destination.Dump());
        }
예제 #26
0
        public static IMapper Start()
        {
            var mapperConfiguration = new MapperConfiguration(
                configuration =>
                {
                    configuration.CreateMap<Common.Models.Insuree, ListInsuree>();
                    configuration.CreateMap<Common.Models.Insuree, DetailInsuree>();
                    configuration.CreateMap<Common.Models.Insuree, AddOrEditInsuree>().ReverseMap();
                    configuration.CreateMap<Common.Models.Address, DetailAddress>();
                    configuration.CreateMap<Common.Models.PhoneNumber, DetailPhoneNumber>();
                    configuration.CreateMap<Common.Models.EmailAddress, DetailEmailAddress>();
                    configuration.CreateMap<Common.Models.Insurance, ListInsurance>();
                    configuration.CreateMap<Common.Models.Insurance, DetailInsurance>();
                });
            mapperConfiguration.AssertConfigurationIsValid();

            return mapperConfiguration.CreateMapper();
        }
예제 #27
0
파일: App.xaml.cs 프로젝트: aiten/CNCLib
		private void AppStartup(object sender, StartupEventArgs e)
		{
            Dependency.Initialize(new LiveDependencyProvider());
			Dependency.Container.RegisterTypesIncludingInternals(
				//				typeof(CNCLib.ServiceProxy.Logic.MachineService).Assembly,
				typeof(CNCLib.ServiceProxy.WebAPI.MachineService).Assembly,
				typeof(CNCLib.Logic.Client.DynItemController).Assembly);
	//			Dependency.Container.RegisterType<IUnitOfWork, UnitOfWork<CNCLibContext>>();

			var config = new MapperConfiguration(cfg =>
				{
//					cfg.AddProfile<LogicAutoMapperProfile>();
					cfg.AddProfile<WpfAutoMapperProfile>();
				});
			config.AssertConfigurationIsValid();

			var mapper = config.CreateMapper();

			Dependency.Container.RegisterInstance<IMapper>(mapper);

			// Open WebAPI Connection
			//
			bool ok = Task.Run(async () =>
			{
				try
				{
					using (var controller = Dependency.Resolve<IMachineService>())
					{
						var m = await controller.GetDetaultMachine();
						if (m == -1)
						{
							throw new ArgumentException("illegal defaulemachne");
						}
					}
					return true;
				}
				catch (Exception ex)
				{
					MessageBox.Show($"Cannot connect to WebAPI: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
					Application.Current.Shutdown();
					return false;
				}
			}).ConfigureAwait(true).GetAwaiter().GetResult();
		}
예제 #28
0
			public void Example()
			{
				var mapperConfig = new MapperConfiguration(cfg =>
				{
					cfg.CreateMap<OrderForm, ICreateOrderMessage>();
				});

				mapperConfig.AssertConfigurationIsValid();

			    var mapper = mapperConfig.CreateMapper();

				var order = new OrderForm
					{
						Customer = new Customer {Name = "Bob Smith"}
					};

				var message = mapper.Map<OrderForm, ICreateOrderMessage>(order);

				message.CustomerName.ShouldEqual("Bob Smith");
			}
예제 #29
0
            public void Example()
            {
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<OrderDto, Order>()
                        .ForMember(dest => dest.Id, opt => opt.Ignore());
                });

                config.AssertConfigurationIsValid();

                var orderDto = new OrderDto {Amount = 50m};

                var order = new Order {Id = 4};

                var mapper = config.CreateMapper();

                mapper.Map(orderDto, order);

                order.Amount.ShouldEqual(50m);
            }
예제 #30
0
        public List<EmpOrdersViewModel> GetEmpOrders()
        {
            List<EmpOrdersViewModel> models = new List<EmpOrdersViewModel>();

            // 取得所有員工資料
            var DbResult = db.Get().ToList();

            //Mapping
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Employees, EmpOrdersViewModel>()
                .ForMember(c => c.EmployeeName
                , x => x.MapFrom(d => string.Format("{0} {1}", d.FirstName, d.LastName)))
                .ForMember(c => c.OrderCount, x => x.MapFrom(d => d.Orders.Count())));

            config.AssertConfigurationIsValid();

            var mapper = config.CreateMapper();

            return mapper.Map<List<Employees>, List<EmpOrdersViewModel>>(DbResult)
                .OrderByDescending(c => c.OrderCount).ToList();
        }
예제 #31
0
        public void ThenShouldUseValidConfiguration()
        {
            var config = new MapperConfiguration(c => c.AddProfiles(typeof(HealthCheckMappings), typeof(PaymentMappings)));

            config.AssertConfigurationIsValid();
        }
예제 #32
0
 public void AutoMapper_Configuration_IsValid()
 {
     Configuration.AssertConfigurationIsValid();
 }
예제 #33
0
        /// <summary>
        /// Initializes the application object.
        /// </summary>
        /// <param name="api">The current api</param>
        private void Initialize()
        {
            if (!_isInitialized)
            {
                lock (_mutex)
                {
                    if (!_isInitialized)
                    {
                        // Configure object mapper
                        var mapperConfig = new MapperConfiguration(cfg =>
                        {
                            cfg.CreateMap <Data.Alias, Data.Alias>()
                            .ForMember(a => a.Id, o => o.Ignore())
                            .ForMember(a => a.Created, o => o.Ignore());
                            cfg.CreateMap <Data.Category, Data.Category>()
                            .ForMember(c => c.Id, o => o.Ignore())
                            .ForMember(c => c.Created, o => o.Ignore());
                            cfg.CreateMap <Data.MediaFolder, Data.MediaFolder>()
                            .ForMember(f => f.Id, o => o.Ignore())
                            .ForMember(f => f.Created, o => o.Ignore())
                            .ForMember(f => f.Media, o => o.Ignore());
                            cfg.CreateMap <Data.MediaFolder, Models.MediaStructureItem>()
                            .ForMember(f => f.Level, o => o.Ignore())
                            .ForMember(f => f.Items, o => o.Ignore());
                            cfg.CreateMap <Data.Page, Models.PageBase>()
                            .ForMember(p => p.TypeId, o => o.MapFrom(m => m.PageTypeId))
                            .ForMember(p => p.Permalink, o => o.MapFrom(m => "/" + m.Slug))
                            .ForMember(p => p.Blocks, o => o.Ignore());
                            cfg.CreateMap <Models.PageBase, Data.Page>()
                            .ForMember(p => p.PageTypeId, o => o.MapFrom(m => m.TypeId))
                            .ForMember(p => p.Blocks, o => o.Ignore())
                            .ForMember(p => p.Fields, o => o.Ignore())
                            .ForMember(p => p.Created, o => o.Ignore())
                            .ForMember(p => p.LastModified, o => o.Ignore())
                            .ForMember(p => p.PageType, o => o.Ignore())
                            .ForMember(p => p.Site, o => o.Ignore())
                            .ForMember(p => p.Parent, o => o.Ignore());
                            cfg.CreateMap <Data.Page, Models.SitemapItem>()
                            .ForMember(p => p.MenuTitle, o => o.Ignore())
                            .ForMember(p => p.Level, o => o.Ignore())
                            .ForMember(p => p.Items, o => o.Ignore())
                            .ForMember(p => p.PageTypeName, o => o.Ignore())
                            .ForMember(p => p.Permalink, o => o.MapFrom(d => !d.ParentId.HasValue && d.SortOrder == 0 ? "/" : "/" + d.Slug));
                            cfg.CreateMap <Data.Param, Data.Param>()
                            .ForMember(p => p.Id, o => o.Ignore())
                            .ForMember(p => p.Created, o => o.Ignore());
                            cfg.CreateMap <Data.Post, Models.PostBase>()
                            .ForMember(p => p.TypeId, o => o.MapFrom(m => m.PostTypeId))
                            .ForMember(p => p.Permalink, o => o.MapFrom(m => "/" + m.Blog.Slug + "/" + m.Slug))
                            .ForMember(p => p.Blocks, o => o.Ignore());
                            cfg.CreateMap <Models.PostBase, Data.Post>()
                            .ForMember(p => p.PostTypeId, o => o.MapFrom(m => m.TypeId))
                            .ForMember(p => p.CategoryId, o => o.MapFrom(m => m.Category.Id))
                            .ForMember(p => p.Blocks, o => o.Ignore())
                            .ForMember(p => p.Fields, o => o.Ignore())
                            .ForMember(p => p.Created, o => o.Ignore())
                            .ForMember(p => p.LastModified, o => o.Ignore())
                            .ForMember(p => p.PostType, o => o.Ignore())
                            .ForMember(p => p.Blog, o => o.Ignore())
                            .ForMember(p => p.Category, o => o.Ignore())
                            .ForMember(p => p.Tags, o => o.Ignore());
                            cfg.CreateMap <Data.Site, Data.Site>()
                            .ForMember(s => s.Id, o => o.Ignore())
                            .ForMember(s => s.Created, o => o.Ignore());
                            cfg.CreateMap <Data.Site, Models.SiteContentBase>()
                            .ForMember(s => s.TypeId, o => o.MapFrom(m => m.SiteTypeId));
                            cfg.CreateMap <Models.SiteContentBase, Data.Site>()
                            .ForMember(s => s.SiteTypeId, o => o.Ignore())
                            .ForMember(s => s.InternalId, o => o.Ignore())
                            .ForMember(s => s.Description, o => o.Ignore())
                            .ForMember(s => s.Hostnames, o => o.Ignore())
                            .ForMember(s => s.IsDefault, o => o.Ignore())
                            .ForMember(s => s.Fields, o => o.Ignore())
                            .ForMember(s => s.Created, o => o.Ignore())
                            .ForMember(s => s.LastModified, o => o.Ignore());
                            cfg.CreateMap <Data.Tag, Data.Tag>()
                            .ForMember(t => t.Id, o => o.Ignore())
                            .ForMember(t => t.Created, o => o.Ignore());
                        });
                        mapperConfig.AssertConfigurationIsValid();
                        _mapper = mapperConfig.CreateMapper();

                        // Setup media types
                        _mediaTypes.Documents.Add(".pdf", "application/pdf");
                        _mediaTypes.Images.Add(".jpg", "image/jpeg");
                        _mediaTypes.Images.Add(".jpeg", "image/jpeg");
                        _mediaTypes.Images.Add(".png", "image/png");
                        _mediaTypes.Videos.Add(".mp4", "video/mp4");

                        // Compose content types
                        _contentTypes.Register <Models.IPage>("Page", "Page");
                        _contentTypes.Register <Models.IBlogPage>("Blog", "Archive", true);

                        // Compose field types
                        _fields.Register <Extend.Fields.CheckBoxField>();
                        _fields.Register <Extend.Fields.DateField>();
                        _fields.Register <Extend.Fields.DocumentField>();
                        _fields.Register <Extend.Fields.HtmlField>();
                        _fields.Register <Extend.Fields.ImageField>();
                        _fields.Register <Extend.Fields.MarkdownField>();
                        _fields.Register <Extend.Fields.MediaField>();
                        _fields.Register <Extend.Fields.NumberField>();
                        _fields.Register <Extend.Fields.PageField>();
                        _fields.Register <Extend.Fields.PostField>();
                        _fields.Register <Extend.Fields.StringField>();
                        _fields.Register <Extend.Fields.TextField>();
                        _fields.Register <Extend.Fields.VideoField>();

                        // Compose block types
                        _blocks.Register <Extend.Blocks.HtmlBlock>();
                        _blocks.Register <Extend.Blocks.HtmlColumnBlock>();
                        _blocks.Register <Extend.Blocks.ImageBlock>();
                        _blocks.Register <Extend.Blocks.QuoteBlock>();
                        _blocks.Register <Extend.Blocks.TextBlock>();

                        // Compose serializers
                        _serializers.Register <Extend.Fields.CheckBoxField>(new CheckBoxFieldSerializer <Extend.Fields.CheckBoxField>());
                        _serializers.Register <Extend.Fields.DateField>(new DateFieldSerializer());
                        _serializers.Register <Extend.Fields.DocumentField>(new DocumentFieldSerializer());
                        _serializers.Register <Extend.Fields.HtmlField>(new StringFieldSerializer <Extend.Fields.HtmlField>());
                        _serializers.Register <Extend.Fields.MarkdownField>(new StringFieldSerializer <Extend.Fields.MarkdownField>());
                        _serializers.Register <Extend.Fields.MediaField>(new MediaFieldSerializer());
                        _serializers.Register <Extend.Fields.NumberField>(new IntegerFieldSerializer <Extend.Fields.NumberField>());
                        _serializers.Register <Extend.Fields.PageField>(new PageFieldSerializer());
                        _serializers.Register <Extend.Fields.PostField>(new PostFieldSerializer());
                        _serializers.Register <Extend.Fields.StringField>(new StringFieldSerializer <Extend.Fields.StringField>());
                        _serializers.Register <Extend.Fields.TextField>(new StringFieldSerializer <Extend.Fields.TextField>());
                        _serializers.Register <Extend.Fields.ImageField>(new ImageFieldSerializer());
                        _serializers.Register <Extend.Fields.VideoField>(new VideoFieldSerializer());

                        // Create markdown converter
                        _markdown = new DefaultMarkdown();

                        // Register permissions
                        _permissions["Core"].Add(new PermissionItem
                        {
                            Name  = Permission.PagePreview,
                            Title = "Page Preview"
                        });
                        _permissions["Core"].Add(new PermissionItem
                        {
                            Name  = Permission.PostPreview,
                            Title = "Post Preview"
                        });

                        // Initialize all modules
                        foreach (var module in _modules)
                        {
                            module.Instance.Init();
                        }

                        _isInitialized = true;
                    }
                }
            }
        }
예제 #34
0
        /// <summary>
        /// Create automapping.
        /// </summary>
        static Module()
        {
            var mapperConfig = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Data.Alias, Data.Alias>()
                .ForMember(a => a.Id, o => o.Ignore())
                .ForMember(a => a.Created, o => o.Ignore());
                cfg.CreateMap <Data.Category, Data.Category>()
                .ForMember(c => c.Id, o => o.Ignore())
                .ForMember(c => c.Created, o => o.Ignore());
                cfg.CreateMap <Data.MediaFolder, Data.MediaFolder>()
                .ForMember(f => f.Id, o => o.Ignore())
                .ForMember(f => f.Created, o => o.Ignore())
                .ForMember(f => f.Media, o => o.Ignore());
                cfg.CreateMap <Data.MediaFolder, Models.MediaStructureItem>()
                .ForMember(f => f.Level, o => o.Ignore())
                .ForMember(f => f.Items, o => o.Ignore());
                cfg.CreateMap <Data.Page, Models.PageBase>()
                .ForMember(p => p.TypeId, o => o.MapFrom(m => m.PageTypeId))
                .ForMember(p => p.Permalink, o => o.MapFrom(m => "/" + m.Slug))
                .ForMember(p => p.Blocks, o => o.Ignore());
                cfg.CreateMap <Models.PageBase, Data.Page>()
                .ForMember(p => p.PageTypeId, o => o.MapFrom(m => m.TypeId))
                .ForMember(p => p.Blocks, o => o.Ignore())
                .ForMember(p => p.Fields, o => o.Ignore())
                .ForMember(p => p.Created, o => o.Ignore())
                .ForMember(p => p.LastModified, o => o.Ignore())
                .ForMember(p => p.PageType, o => o.Ignore())
                .ForMember(p => p.Site, o => o.Ignore())
                .ForMember(p => p.Parent, o => o.Ignore());
                cfg.CreateMap <Data.Page, Models.SitemapItem>()
                .ForMember(p => p.MenuTitle, o => o.Ignore())
                .ForMember(p => p.Level, o => o.Ignore())
                .ForMember(p => p.Items, o => o.Ignore())
                .ForMember(p => p.PageTypeName, o => o.Ignore())
                .ForMember(p => p.Permalink, o => o.MapFrom(d => !d.ParentId.HasValue && d.SortOrder == 0 ? "/" : "/" + d.Slug));
                cfg.CreateMap <Data.Param, Data.Param>()
                .ForMember(p => p.Id, o => o.Ignore())
                .ForMember(p => p.Created, o => o.Ignore());
                cfg.CreateMap <Data.Post, Models.PostBase>()
                .ForMember(p => p.TypeId, o => o.MapFrom(m => m.PostTypeId))
                .ForMember(p => p.Permalink, o => o.Ignore())
                .ForMember(p => p.Blocks, o => o.Ignore());
                cfg.CreateMap <Data.PostTag, Models.Taxonomy>()
                .ForMember(p => p.Id, o => o.MapFrom(m => m.TagId))
                .ForMember(p => p.Title, o => o.MapFrom(m => m.Tag.Title))
                .ForMember(p => p.Slug, o => o.MapFrom(m => m.Tag.Slug));
                cfg.CreateMap <Models.PostBase, Data.Post>()
                .ForMember(p => p.PostTypeId, o => o.MapFrom(m => m.TypeId))
                .ForMember(p => p.CategoryId, o => o.MapFrom(m => m.Category.Id))
                .ForMember(p => p.Blocks, o => o.Ignore())
                .ForMember(p => p.Fields, o => o.Ignore())
                .ForMember(p => p.Created, o => o.Ignore())
                .ForMember(p => p.LastModified, o => o.Ignore())
                .ForMember(p => p.PostType, o => o.Ignore())
                .ForMember(p => p.Blog, o => o.Ignore())
                .ForMember(p => p.Category, o => o.Ignore())
                .ForMember(p => p.Tags, o => o.Ignore());
                cfg.CreateMap <Data.Site, Data.Site>()
                .ForMember(s => s.Id, o => o.Ignore())
                .ForMember(s => s.Created, o => o.Ignore());
                cfg.CreateMap <Data.Site, Models.SiteContentBase>()
                .ForMember(s => s.TypeId, o => o.MapFrom(m => m.SiteTypeId));
                cfg.CreateMap <Models.SiteContentBase, Data.Site>()
                .ForMember(s => s.SiteTypeId, o => o.Ignore())
                .ForMember(s => s.InternalId, o => o.Ignore())
                .ForMember(s => s.Description, o => o.Ignore())
                .ForMember(s => s.Hostnames, o => o.Ignore())
                .ForMember(s => s.IsDefault, o => o.Ignore())
                .ForMember(s => s.Culture, o => o.Ignore())
                .ForMember(s => s.Fields, o => o.Ignore())
                .ForMember(s => s.Created, o => o.Ignore())
                .ForMember(s => s.LastModified, o => o.Ignore())
                .ForMember(s => s.ContentLastModified, o => o.Ignore());
                cfg.CreateMap <Data.Tag, Data.Tag>()
                .ForMember(t => t.Id, o => o.Ignore())
                .ForMember(t => t.Created, o => o.Ignore());
            });

            mapperConfig.AssertConfigurationIsValid();
            Mapper = mapperConfig.CreateMapper();
        }
예제 #35
0
 public void Shopline_ConfigMapper()
 {
     config.AssertConfigurationIsValid();
 }
예제 #36
0
        public void TestModelMapping()
        {
            var config = new MapperConfiguration(opt => opt.AddProfile <ModelMapperProfile>());

            Assert.DoesNotThrow(() => config.AssertConfigurationIsValid());
        }
예제 #37
0
 public void Map_Should_HaveValidConfig()
 {
     _mapperConfig.AssertConfigurationIsValid();
 }
예제 #38
0
 public void Then_All_Properties_Are_Implemented() =>
 _config.AssertConfigurationIsValid();
예제 #39
0
        public void XmlBuilderProfile_ConfigurationIsValid()
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile <XmlBuilderProfile>());

            config.AssertConfigurationIsValid();
        }
예제 #40
0
        public void Mapper_WhenMapperIsInitiated_ConfigurationIsValid()
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile <PolicyProfile>());

            config.AssertConfigurationIsValid();
        }
예제 #41
0
 public void ValidMapping()
 {
     FromCifProfileConfiguration.AssertConfigurationIsValid();
 }
예제 #42
0
 public void AutoMapperConfigurationIsValid()
 {
     sut.AssertConfigurationIsValid();
 }
예제 #43
0
 public void ValidMapping()
 {
     ToViewProfileConfiguration.AssertConfigurationIsValid();
 }
        public OrganizationUserDataMapper()
        {
            var automapConfig = new MapperConfiguration(config =>
            {
                config
                .CreateMap <EFEntity.OrganizationUserEntity, GetOrganizationUserResult>()
                .ForMember(o => o.OrganizationUserId, d => d.MapFrom(e => e.OrganizationUserEntityId))
                .ForMember(o => o.ProfileId, d => d.MapFrom(e => e.Profile.ProfileEntityId))
                .ForMember(o => o.ProfileValues, d => d.MapFrom(e => e.Profile.ProfileValues))
                .ForMember(o => o.Groups, d => d.MapFrom(e => e.Groups))
                .ForMember(o => o.HasAcceptedInvitation, d => d.Condition(e => e.UserInvitation != null))
                .ForMember(o => o.HasAcceptedInvitation, d => d.MapFrom(e => e.UserInvitation.AcceptedAt.HasValue))
                ;

                config
                .CreateMap <EFEntity.OrganizationUserEntity, GetOrganizationUserByExternalUserIdResult>()
                .ForMember(o => o.OrganizationUserId, d => d.MapFrom(e => e.OrganizationUserEntityId))
                .ForMember(o => o.Username, d => d.MapFrom(e => e.Username))
                .ForMember(o => o.UserType, d => d.MapFrom(e => e.UserType))
                ;

                config
                .CreateMap <EFEntity.OrganizationUserEntity, GetOrganizationAdminResult>()
                .ForMember(o => o.OrganizationUserId, d => d.MapFrom(e => e.OrganizationUserEntityId))
                ;

                config.CreateMap <EFEntity.GroupMemberEntity, OrganizationUserGroupListModel>()
                .ForMember(d => d.GroupId, d => d.MapFrom(s => s.Group.GroupEntityId))
                .ForMember(d => d.GroupName, d => d.MapFrom(s => s.Group.Name))
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

                config.CreateMap <EFEntity.ProfileValueEntity, ProfileValuesListModel>();

                config.CreateMap <EFEntity.AssociatedOrganizationUserEntity, AssociationOrganizationUserListModel>()
                .ForMember(d => d.OrganizationUserId, d => d.MapFrom(s => s.OrganizationUserId2));

                config
                .CreateMap <CreateOrganizationUserCommand, EFEntity.OrganizationUserEntity>()
                .ForMember(o => o.OrganizationUserEntityId, d => d.Ignore())
                .ForMember(o => o.Organization, d => d.Ignore())
                .ForMember(o => o.AssociatedOrganizationUsers, d => d.Ignore())
                .ForMember(o => o.UserInvitation, d => d.Ignore())
                .ForMember(o => o.Profile, d => d.Ignore())
                .ForMember(o => o.RollbackedAt, d => d.Ignore())
                .ForMember(o => o.DeletedAt, d => d.Ignore())
                .ForMember(o => o.CreatedAt, d => d.Ignore())
                .ForMember(o => o.UpdatedAt, d => d.Ignore())
                .ForMember(o => o.Groups, d => d.Ignore())
                .ForMember(o => o.LastLoginAt, d => d.Ignore())
                .ForMember(o => o.Roles, d => d.Ignore())
                ;
                config
                .CreateMap <EFEntity.OrganizationUserEntity, EFEntity.OrganizationUserEntity>()
                .ForMember(o => o.OrganizationUserEntityId, d => d.Ignore())
                ;
                config
                .CreateMap <EFEntity.OrganizationUserEntity, OrganizationUserListModel>()
                .ForMember(o => o.OrganizationUserId, d => d.MapFrom(e => e.OrganizationUserEntityId))
                .ForMember(o => o.ProfileId, d => d.MapFrom(e => e.Profile.ProfileEntityId))
                .ForMember(o => o.ProfileValues, d => d.MapFrom(e => e.Profile.ProfileValues))
                ;

                config
                .CreateMap <EFEntity.OrganizationUserEntity, OrganizationUsersListModel>()
                .ForMember(o => o.OrganizationUserId, d => d.MapFrom(e => e.OrganizationUserEntityId))
                .ForMember(o => o.Roles, d => d.Ignore())
                .ForMember(o => o.LastLoginTime, d => d.MapFrom(e => e.LastLoginAt))
                ;

                //associations
                config
                .CreateMap <CreateOrganizationUsersAssociationCommand, EFEntity.AssociatedOrganizationUserEntity>()
                .ForMember(d => d.AssociatedOrganizationUserEntityId, d => d.Ignore())
                .ForMember(d => d.OrganizationUser, d => d.Ignore())
                .ForMember(d => d.RollbackedAt, d => d.Ignore())
                .ForMember(d => d.CreatedAt, d => d.Ignore())
                .ForMember(d => d.CreatedBy, d => d.Ignore())
                .ForMember(d => d.UpdatedAt, d => d.Ignore())
                .ForMember(d => d.UpdatedBy, d => d.Ignore())
                .ForMember(d => d.DeletedAt, d => d.Ignore())
                .ForMember(d => d.DeletedBy, d => d.Ignore())
                ;
            });

            automapConfig.AssertConfigurationIsValid();
            this.Mapper = automapConfig.CreateMapper();
        }
예제 #45
0
        static BaseService()
        {
            //_mapperConfiguration = new MapperConfiguration(cfg => cfg.CreateMap(typeof(User),typeof(ViewModel.Register.IndexModel)));
            _mapperConfiguration = new MapperConfiguration(cfg =>
            {
                //cfg.CreateMap<User, ViewModel.Register.IndexModel>().ReverseMap();
                #region User-->Register 的双向映射配置
                cfg.CreateMap <User, ViewModel.Register.UserModel>()         //配置映射     TSource(左)映射到TDestition(右)
                .ForMember(m => m.UserId, opt => opt.MapFrom(u => u.Id))
                .ForMember(m => m.UserName, opt => opt.MapFrom(u => u.Name)) //具体的映射   TDestition(左)   TSource(右)
                .ForMember(m => m.Password, opt => opt.MapFrom(u => u.Password))
                .ForMember(m => m.InviterName, opt => opt.MapFrom(u => u.Inviter.Name))
                .ForMember(m => m.InvitingCode, opt => opt.MapFrom(u => u./*Inviter.*/ InvitingCode))
                .ForMember(m => m.ComfirmPassword, opt => opt.Ignore()) //忽略某一属性
                .ForMember(m => m.Captcha, opt => opt.Ignore())         //忽略验证码
                .ForMember(m => m.EmailAddress, opt => opt.MapFrom(u => u.BindingEmail.Address))
                .ForMember(m => m.EmailCode, opt => opt.MapFrom(u => u.BindingEmail.Code))
                //.ForMember(m => m.ExprieTime, opt => opt.MapFrom(u => u.BindingEmail.Expires))
                .ForMember(m => m.EmailIsActivate, opt => opt.MapFrom(u => u.BindingEmail.IsAvtivate))
                //.ForMember(m => m.InputTime, opt => opt.Ignore())
                .ReverseMap()
                .ForMember(u => u.Id, opt => opt.NullSubstitute(0))   //null值处理
                .ForMember(u => u.InvitingCode, opt => opt.Ignore())
                .ForMember(u => u.BindingEmail, opt => opt.MapFrom(m => m));
                #endregion

                cfg.CreateMap <ViewModel.Register.UserModel, Email>(MemberList.None)  //不需要全部映射
                .ForMember(e => e.Address, opt => opt.MapFrom(m => m.EmailAddress))
                ;

                #region Article-->ArticleItemModel 的单向映射配置
                cfg.CreateMap <Article, ViewModel.Article.ArticleItemModel>()
                .ForMember(m => m.PublishTime, opt => opt.MapFrom(a => a.PublishTime))
                .ForMember(m => m.AuthorName, opt => opt.MapFrom(a => a.Author.Name))
                .ForMember(m => m.AuthorId, opt => opt.MapFrom(a => a.UserId))
                .ForMember(m => m.Title, opt => opt.MapFrom(a => a.Title))
                .ForMember(m => m.Id, opt => opt.MapFrom(a => a.Id))
                .ForMember(m => m.Body, opt => opt.MapFrom(a => a.Body))
                .ForMember(m => m.KeywordModels, opt => opt.MapFrom(a => a.Keywords.Select(k => k.Keyword)))
                .ForMember(m => m.CommnetCount, opt => opt.MapFrom(a => a.Commnets.Count))
                .ForMember(m => m.AgreeCount, opt => opt.MapFrom(a => a.AgreeCount))
                .ForMember(m => m.DisagreeCount, opt => opt.MapFrom(a => a.DisagreeCount))
                /* .ReverseMap()*/;
                //cfg.CreateMap<User,ViewModel.Article.ArticleItemModel>(MemberList.None)
                //.ForMember(a=> a.AuthorName, opt => opt.MapFrom(u => u.Name));
                #endregion

                #region Article-->ArticleSingleModel 的单向映射配置
                cfg.CreateMap <Article, ViewModel.Article.ArticleSingleModel>(MemberList.None)
                .ForMember(m => m.PublishTime, opt => opt.MapFrom(a => a.PublishTime))
                .ForMember(m => m.AuthorName, opt => opt.MapFrom(a => a.Author.Name))
                .ForMember(m => m.AuthorId, opt => opt.MapFrom(a => a.UserId))
                .ForMember(m => m.Title, opt => opt.MapFrom(a => a.Title))
                .ForMember(m => m.Id, opt => opt.MapFrom(a => a.Id))
                .ForMember(m => m.Body, opt => opt.MapFrom(a => a.Body))
                .ForMember(m => m.KeywordModels, opt => opt.MapFrom(a => a.Keywords.Select(k => k.Keyword)))
                .ForMember(m => m.CommnetCount, opt => opt.MapFrom(a => a.Commnets.Count))
                .ForMember(m => m.AgreeCount, opt => opt.MapFrom(a => a.AgreeCount))
                .ForMember(m => m.DisagreeCount, opt => opt.MapFrom(a => a.DisagreeCount));
                #endregion

                #region Article-->ArticleEditModel 的双向映射配置
                cfg.CreateMap <Article, ViewModel.Article.ArticleEditModel>(MemberList.None)
                .ForMember(m => m.PublishTime, opt => opt.MapFrom(a => a.PublishTime))
                .ForMember(m => m.AuthorName, opt => opt.MapFrom(a => a.Author.Name))
                .ForMember(m => m.AuthorId, opt => opt.MapFrom(a => a.UserId))
                .ForMember(m => m.Title, opt => opt.MapFrom(a => a.Title))
                .ForMember(m => m.Id, opt => opt.MapFrom(a => a.Id))
                .ForMember(m => m.Body, opt => opt.MapFrom(a => a.Body))
                //.ForMember(m => m.KeywordModels, opt => opt.MapFrom(a => a.Keywords))
                .ForMember(m => m.CommnetCount, opt => opt.MapFrom(a => a.Commnets.Count))
                .ForMember(m => m.AgreeCount, opt => opt.MapFrom(a => a.AgreeCount))
                .ForMember(m => m.DisagreeCount, opt => opt.MapFrom(a => a.DisagreeCount))
                .ReverseMap()
                .ForMember(a => a.PublishTime, opt => opt.MapFrom(m => m.PublishTime))
                .ForMember(a => a.Title, opt => opt.MapFrom(m => m.Title))
                .ForMember(a => a.AgreeCount, opt => opt.MapFrom(m => m.AgreeCount))
                .ForMember(a => a.DisagreeCount, opt => opt.MapFrom(m => m.DisagreeCount))
                .ForMember(a => a.Author, opt => opt.MapFrom(m => m))
                //.ForMember(a => a.Keywords, opt => opt.Ignore())

                ;

                cfg.CreateMap <ViewModel.Article.ArticleEditModel, User>(MemberList.None)
                .ForMember(u => u.Name, opt => opt.MapFrom(m => m.AuthorName))
                .ForMember(u => u.Id, opt => opt.MapFrom(m => m.AuthorName));
                #endregion

                #region ArticleEditModel-->Article 的单向映射配置
                cfg.CreateMap <ViewModel.Article.ArticleNewModel, Article>(MemberList.None)
                .ForMember(a => a.Title, opt => opt.MapFrom(m => m.Title))
                .ForMember(a => a.Body, opt => opt.MapFrom(m => m.Body))
                .ForMember(a => a.PublishTime, opt => opt.MapFrom(m => m.PublishTime))
                .ForMember(a => a.Id, opt => opt.NullSubstitute(0))
                ;
                #endregion

                cfg.CreateMap <Keyword, ViewModel.Keyword.KeywordModel>();

                #region 个人资料的映射
                cfg.CreateMap <User, ViewModel.Personal.PersonalInformationModel>(MemberList.None)
                .ForMember(m => m.IconPath, opt => opt.MapFrom(u => u.IconPath))
                .ForMember(m => m.UserId, opt => opt.MapFrom(u => u.Id))
                .ForMember(m => m.UserName, opt => opt.MapFrom(u => u.Name))
                .ForMember(m => m.Password, opt => opt.MapFrom(u => u.Password))
                .ForMember(m => m.InvitingCode, opt => opt.MapFrom(u => u.InvitingCode))
                .ForMember(m => m.InviterId, opt => opt.MapFrom(u => u.Inviter.Id))
                .ForMember(m => m.ArticleId, opt => opt.MapFrom(u => u.ArticleId))
                .ReverseMap();
                #endregion


                cfg.CreateMap <User, ViewModel.LogOn.LogOnModel>()
                .ForMember(m => m.UserId, opt => opt.MapFrom(u => u.Id))
                .ForMember(m => m.UserName, opt => opt.MapFrom(u => u.Name))
                .ForMember(m => m.Password, opt => opt.MapFrom(u => u.Password))
                .ForMember(m => m.Captcha, opt => opt.Ignore())
                .ReverseMap()
                ;

                cfg.CreateMap <User, ViewModel.Password.ChangeModel>(MemberList.None)
                .ForMember(m => m.PresentPassword, opt => opt.MapFrom(u => u.Password))
                .ForMember(m => m.Id, opt => opt.MapFrom(u => u.Id))
                .ForMember(m => m.UpdatePassword, opt => opt.Ignore())
                .ForMember(m => m.ComfirmPassword, opt => opt.Ignore())
                .ReverseMap()
                .ForMember(u => u.Password, opt => opt.MapFrom(m => m.UpdatePassword));

                cfg.CreateMap <User, ViewModel.Password.ForgetModel>(MemberList.None)
                .ForMember(m => m.EmailAddress, opt => opt.MapFrom(u => u.BindingEmail.Address))
                .ForMember(m => m.Id, opt => opt.MapFrom(u => u.Id))
                .ForMember(m => m.UserName, opt => opt.MapFrom(u => u.Name))
                .ForMember(m => m.VerificationCode, opt => opt.Ignore())
                .ReverseMap()
                .ForMember(u => u.BindingEmail, opt => opt.MapFrom(m => m));

                cfg.CreateMap <ViewModel.Password.ForgetModel, Email>(MemberList.None)
                .ForMember(e => e.Address, opt => opt.MapFrom(m => m.EmailAddress));

                cfg.CreateMap <ViewModel.Password.ResetModel, User>(MemberList.None)
                .ForMember(u => u.Password, opt => opt.MapFrom(m => m.UpdatePassword))
                .ReverseMap()
                .ForMember(m => m.Id, opt => opt.MapFrom(u => u.Id))
                .ForMember(m => m.UpdatePassword, opt => opt.Ignore())
                .ForMember(m => m.ComfirmPassword, opt => opt.Ignore());
            });
#if DEBUG
            _mapperConfiguration.AssertConfigurationIsValid();
#endif
        }
예제 #46
0
 /// <summary>
 /// Asserts the configuration is valid.
 /// </summary>
 public void AssertConfigurationIsValid()
 {
     _configuration.AssertConfigurationIsValid();
 }
예제 #47
0
        private void Initialize()
        {
            if (MapperConfiguration == null)
            {
                MapperConfiguration = new MapperConfiguration(cfg =>
                {
                    cfg.AddExpressionMapping();

                    cfg.AddProfile <ParameterToDescriptorMappingProfile>();
                    cfg.AddProfile <DescriptorToOperatorMappingProfile>();
                    cfg.AddProfile <EnrollmentProfile>();
                    cfg.AddProfile <ExpansionParameterToDescriptorMappingProfile>();
                    cfg.AddProfile <ExpansionDescriptorToOperatorMappingProfile>();
                });
            }
            MapperConfiguration.AssertConfigurationIsValid();
            serviceProvider = new ServiceCollection()
                              .AddDbContext <EnrollmentContext>
                              (
                options => options.UseSqlServer
                (
                    @"Server=(localdb)\mssqllocaldb;Database=InsertMoreInfoTest;ConnectRetryCount=0"
                ),
                ServiceLifetime.Transient
                              )
                              .AddLogging
                              (
                loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.Services.AddSingleton <ILoggerProvider>
                (
                    serviceProvider => new XUnitLoggerProvider(this.output)
                );
                loggingBuilder.AddFilter <XUnitLoggerProvider>("*", LogLevel.None);
                loggingBuilder.AddFilter <XUnitLoggerProvider>("Enrollment.Bsl.Flow", LogLevel.Trace);
            }
                              )
                              .AddTransient <IEnrollmentStore, EnrollmentStore>()
                              .AddTransient <IEnrollmentRepository, EnrollmentRepository>()
                              .AddSingleton <AutoMapper.IConfigurationProvider>
                              (
                MapperConfiguration
                              )
                              .AddTransient <IMapper>(sp => new Mapper(sp.GetRequiredService <AutoMapper.IConfigurationProvider>(), sp.GetService))
                              .AddTransient <IFlowManager, FlowManager>()
                              .AddTransient <FlowActivityFactory, FlowActivityFactory>()
                              .AddTransient <DirectorFactory, DirectorFactory>()
                              .AddTransient <ICustomActions, CustomActions>()
                              .AddTransient <IGetItemFilterBuilder, GetItemFilterBuilder>()
                              .AddSingleton <FlowDataCache, FlowDataCache>()
                              .AddSingleton <Progress, Progress>()
                              .AddSingleton <IRulesCache>(sp =>
            {
                return(Bsl.Flow.Rules.RulesService.LoadRules().GetAwaiter().GetResult());
            })
                              .BuildServiceProvider();

            ReCreateDataBase(serviceProvider.GetRequiredService <EnrollmentContext>());
            DatabaseSeeder.Seed_Database(serviceProvider.GetRequiredService <IEnrollmentRepository>()).Wait();
        }
예제 #48
0
        public void CorrectlyConfigured()
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile <ApplicationProfile>());

            config.AssertConfigurationIsValid();
        }
        public void AutoMapper_Configuration_IsValid()
        {
            var config = new MapperConfiguration(cfg => cfg.AddProfile <BotSettingsProfile>());

            config.AssertConfigurationIsValid();
        }
예제 #50
0
        public void TestMapping()
        {
            MapperConfiguration cfg = new MapperConfiguration(cfg => cfg.AddMaps(typeof(Backend.Startup)));

            cfg.AssertConfigurationIsValid();

            IMapper mapper = cfg.CreateMapper();

            Assert.NotNull(mapper);

            #region Current
            OpenWeathermapCurrent currentModel = JsonSerializer.Deserialize <OpenWeathermapCurrent>(
                TestUtilities.GetOpenWeathermapCurrentWeatherJson());
            Weather current = mapper.Map <OpenWeathermapCurrent, Weather>(currentModel);

            Assert.NotNull(current);
            Assert.Equal("Klarer Himmel", current.CloudDescription);
            Assert.Equal(new System.DateTime(2020, 8, 1, 4, 6, 25), current.DateTime);
            Assert.Equal(14.36, current.FeelsLikeTemperature, 2);
            Assert.Equal(82, current.Humidity);
            Assert.Equal(17.22, current.MaximumTemperature, 2);
            Assert.Equal(15, current.MinimumTemperature, 2);
            Assert.Equal(1016, current.Pressure);
            Assert.Equal(15.71, current.Temperature, 2);
            Assert.Equal(110, current.WindDirection);
            Assert.Equal(3.1, current.Windspeed, 1);
            Assert.Equal("01d", current.Icon);
            #endregion

            #region Forecast
            OpenWeathermapForecast forecastModel = JsonSerializer.Deserialize <OpenWeathermapForecast>(
                TestUtilities.GetOpenWeathermapForcastJson());
            Weather[] forecasts = mapper.Map <WeatherList[], Weather[]>(forecastModel.list);

            Assert.NotNull(forecasts);
            Assert.Equal(40, forecasts.Length);

            var forecast = forecasts[0];
            Assert.Equal("Bedeckt", forecast.CloudDescription);
            Assert.Equal(new System.DateTime(2020, 7, 30, 21, 0, 0), forecast.DateTime);
            Assert.Equal(15.46, forecast.FeelsLikeTemperature, 2);
            Assert.Equal(76, forecast.Humidity);
            Assert.Equal(15.87, forecast.MaximumTemperature, 2);
            Assert.Equal(13.58, forecast.MinimumTemperature, 2);
            Assert.Equal(1020, forecast.Pressure);
            Assert.Equal(15.87, forecast.Temperature, 2);
            Assert.Equal(272, forecast.WindDirection);
            Assert.Equal(1.32, forecast.Windspeed, 2);
            Assert.Equal("04n", forecast.Icon);

            forecast = forecasts[4];
            Assert.Equal("Ein paar Wolken", forecast.CloudDescription);
            Assert.Equal(new System.DateTime(2020, 7, 31, 9, 0, 0), forecast.DateTime);
            Assert.Equal(20.47, forecast.FeelsLikeTemperature, 2);
            Assert.Equal(59, forecast.Humidity);
            Assert.Equal(21.05, forecast.MaximumTemperature, 2);
            Assert.Equal(21.05, forecast.MinimumTemperature, 2);
            Assert.Equal(1020, forecast.Pressure);
            Assert.Equal(21.05, forecast.Temperature, 2);
            Assert.Equal(327, forecast.WindDirection);
            Assert.Equal(2.03, forecast.Windspeed, 2);
            Assert.Equal("02d", forecast.Icon);
            #endregion
        }
        private static IMapper CreateMapper()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddCollectionMappers();
                cfg.CreateMap <MachineInformation, MachineInformation>().ForAllMembers(o =>
                                                                                       o.Condition((src, dst, srcMember) => CanBeMapped(srcMember)));
                cfg.CreateMap <CPU, CPU>().ForAllMembers(o =>
                                                         o.Condition((src, dst, srcMember) => CanBeMapped(srcMember)));
                cfg.CreateMap <SMBios, SMBios>().ForAllMembers(o =>
                                                               o.Condition((src, dst, srcMember) => CanBeMapped(srcMember)));
                cfg.CreateMap <GPU, GPU>().EqualityComparison((dst, src) => dst.Name == src.Name);
                cfg.CreateMap <RAM, RAM>().EqualityComparison((dst, src) => dst.Name == src.Name);
                cfg.CreateMap <Core, Core>()
                .EqualityComparison((dst, src) => dst.Number == src.Number && dst.Node == src.Node);
                cfg.CreateMap <Cache, Cache>()
                .EqualityComparison((dst, src) => dst.Level == src.Level && dst.Type == src.Type);
                cfg.CreateMap <USBDevice, USBDevice>().EqualityComparison((dst, src) =>
                                                                          dst.VendorID == src.VendorID && dst.ProductID == src.ProductID);
                cfg.CreateMap <Display, Display>().EqualityComparison((dst, src) =>
                                                                      dst.Name == src.Name && dst.Manufacturer == src.Manufacturer);
                cfg.CreateMap <Disk, Disk>().EqualityComparison((dst, src) =>
                                                                dst.Caption == src.Caption && dst.Model == src.Model && dst.Vendor == src.Vendor);
                cfg.CreateMap <MachineInformation.Platforms, MachineInformation.Platforms>()
                .ConvertUsing((src, dst) => src == MachineInformation.Platforms.Unknown ? dst : src);

                cfg.CreateMap <CPU.FeatureFlagECX, CPU.FeatureFlagECX>()
                .ConvertUsing((src, dst) => src == CPU.FeatureFlagECX.NONE ? dst : src);
                cfg.CreateMap <CPU.FeatureFlagEDX, CPU.FeatureFlagEDX>()
                .ConvertUsing((src, dst) => src == CPU.FeatureFlagEDX.NONE ? dst : src);
                cfg.CreateMap <CPU.ExtendedFeatureFlagsF7EBX, CPU.ExtendedFeatureFlagsF7EBX>()
                .ConvertUsing((src, dst) => src == CPU.ExtendedFeatureFlagsF7EBX.NONE ? dst : src);
                cfg.CreateMap <CPU.ExtendedFeatureFlagsF7ECX, CPU.ExtendedFeatureFlagsF7ECX>()
                .ConvertUsing((src, dst) => src == CPU.ExtendedFeatureFlagsF7ECX.NONE ? dst : src);
                cfg.CreateMap <CPU.ExtendedFeatureFlagsF7EDX, CPU.ExtendedFeatureFlagsF7EDX>()
                .ConvertUsing((src, dst) => src == CPU.ExtendedFeatureFlagsF7EDX.NONE ? dst : src);
                cfg.CreateMap <AMDFeatureFlags.FeatureFlagsAPM, AMDFeatureFlags.FeatureFlagsAPM>()
                .ConvertUsing((src, dst) => src == AMDFeatureFlags.FeatureFlagsAPM.NONE ? dst : src);
                cfg.CreateMap <AMDFeatureFlags.FeatureFlagsSVM, AMDFeatureFlags.FeatureFlagsSVM>()
                .ConvertUsing((src, dst) => src == AMDFeatureFlags.FeatureFlagsSVM.NONE ? dst : src);
                cfg.CreateMap <AMDFeatureFlags.ExtendedFeatureFlagsF81ECX, AMDFeatureFlags.ExtendedFeatureFlagsF81ECX>()
                .ConvertUsing((src, dst) => src == AMDFeatureFlags.ExtendedFeatureFlagsF81ECX.NONE ? dst : src);
                cfg.CreateMap <AMDFeatureFlags.ExtendedFeatureFlagsF81EDX, AMDFeatureFlags.ExtendedFeatureFlagsF81EDX>()
                .ConvertUsing((src, dst) => src == AMDFeatureFlags.ExtendedFeatureFlagsF81EDX.NONE ? dst : src);
                cfg.CreateMap <IntelFeatureFlags.FeatureFlagsAPM, IntelFeatureFlags.FeatureFlagsAPM>()
                .ConvertUsing((src, dst) => src == IntelFeatureFlags.FeatureFlagsAPM.NONE ? dst : src);
                cfg.CreateMap <IntelFeatureFlags.TPMFeatureFlagsEAX, IntelFeatureFlags.TPMFeatureFlagsEAX>()
                .ConvertUsing((src, dst) => src == IntelFeatureFlags.TPMFeatureFlagsEAX.NONE ? dst : src);
                cfg.CreateMap <IntelFeatureFlags.ExtendedFeatureFlagsF81ECX, IntelFeatureFlags.ExtendedFeatureFlagsF81ECX
                               >()
                .ConvertUsing((src, dst) => src == IntelFeatureFlags.ExtendedFeatureFlagsF81ECX.NONE ? dst : src);
                cfg.CreateMap <IntelFeatureFlags.ExtendedFeatureFlagsF81EDX, IntelFeatureFlags.ExtendedFeatureFlagsF81EDX
                               >()
                .ConvertUsing((src, dst) => src == IntelFeatureFlags.ExtendedFeatureFlagsF81EDX.NONE ? dst : src);

                cfg.CreateMap <DeviceType, DeviceType>()
                .ConvertUsing((src, dst) => src == DeviceType.UNKNOWN ? dst : src);
            });

            config.AssertConfigurationIsValid();
            return(config.CreateMapper());
        }
예제 #52
0
        public void MapperProfileIsValid()
        {
            var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile <MapperProfile>(); });

            mapperConfiguration.AssertConfigurationIsValid();
        }