当前位置: 首页>>代码示例>>C#>>正文


C# MapperConfiguration.CreateMapper方法代码示例

本文整理汇总了C#中MapperConfiguration.CreateMapper方法的典型用法代码示例。如果您正苦于以下问题:C# MapperConfiguration.CreateMapper方法的具体用法?C# MapperConfiguration.CreateMapper怎么用?C# MapperConfiguration.CreateMapper使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在MapperConfiguration的用法示例。


在下文中一共展示了MapperConfiguration.CreateMapper方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Application_Start

		protected void Application_Start()
		{
			Dependency.Initialize(new LiveDependencyProvider());
			Dependency.Container.RegisterTypesIncludingInternals(
				typeof(CNCLib.ServiceProxy.Logic.MachineService).Assembly,
				typeof(CNCLib.Repository.MachineRepository).Assembly,
				typeof(CNCLib.Logic.Client.DynItemController).Assembly,
				typeof(CNCLib.Logic.MachineController).Assembly);
			Dependency.Container.RegisterType<IUnitOfWork, UnitOfWork<Repository.Context.CNCLibContext>>();

			Dependency.Container.RegisterType<IRest< CNCLib.Logic.Contracts.DTO.Machine>, MachineRest>();
			Dependency.Container.RegisterType<IRest<CNCLib.Logic.Contracts.DTO.LoadOptions>, LoadInfoRest>();
			Dependency.Container.RegisterType<IRest<CNCLib.Logic.Contracts.DTO.Item>, ItemRest>();

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

			var mapper = config.CreateMapper();

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

			AreaRegistration.RegisterAllAreas();
			GlobalConfiguration.Configure(WebApiConfig.Register);
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
		}
开发者ID:aiten,项目名称:CNCLib,代码行数:29,代码来源:Global.asax.cs

示例2: Get

        // <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
        }
开发者ID:chao1017,项目名称:MVC5_Labs,代码行数:27,代码来源:CustomerService.cs

示例3: ConfigureMapper

        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();
        }
开发者ID:briandarley,项目名称:ClientImport,代码行数:25,代码来源:ModelBuilder.cs

示例4: ConfigureServices

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            services.AddCaching();
            services.AddSession();

            // Configuration
            services.Configure<EncryptionConfig>(Configuration.GetSection("Encryption"));
            services.Configure<EmailConfig>(Configuration.GetSection("Email"));
            services.Configure<RedisConfig>(Configuration.GetSection("Redis"));

            // Dependency Injection
            services.AddSingleton<IRedisService, RedisService>();
            services.AddSingleton<IEncryptionService, BasicEncryption>();
            services.AddSingleton<ISchedulerService, SchedulerService>();
            services.AddSingleton<IEmailService, EmailService>();
            services.AddTransient<IMojangService, MojangService>();
            services.AddTransient<IUserService, UserService>();
            services.AddTransient<IUsernameService, UsernameService>();

            // Automapper
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperProfile());
            });
            services.AddSingleton(sp => config.CreateMapper());
        }
开发者ID:AMerkuri,项目名称:MCNotifier,代码行数:29,代码来源:Startup.cs

示例5: Example

        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();
        }
开发者ID:GeertVL,项目名称:AutoMapper,代码行数:30,代码来源:DeepInheritanceIssue.cs

示例6: Fact

        public void Fact()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateProfile("New Profile", profile =>
                {
                    profile.AddMemberConfiguration().AddName<PrePostfixName>(
                            _ => _.AddStrings(p => p.DestinationPostfixes, "Transfer")
                                .AddStrings(p => p.Postfixes, "Transfer")
                                .AddStrings(p => p.DestinationPrefixes, "Trans")
                                .AddStrings(p => p.Prefixes, "Trans"));
                    profile.AddConditionalObjectMapper().Where((s, d) => s.Name.Contains(d.Name) || d.Name.Contains(s.Name));
                });
            });

            var mapper = config.CreateMapper();
            var a2 = mapper.Map<ClientDto>(new Client() { Value= "Test", Transval = "test"});
            a2.ValueTransfer.ShouldEqual("Test");
            a2.val.ShouldEqual("test");

            var a = mapper.Map<Client>(new ClientDto() { ValueTransfer = "TestTransfer", val = "testTransfer"});
            a.Value.ShouldEqual("TestTransfer");
            a.Transval.ShouldEqual("testTransfer");

            var clients = mapper.Map<Client[]>(new[] { new ClientDto() });
            Expression<Func<Client, bool>> expr = c => c.ID < 5;
            var clientExp = mapper.Map<Expression<Func<ClientDto,bool>>>(expr);
        }
开发者ID:RahmanM,项目名称:AutoMapper,代码行数:28,代码来源:ConvensionTest.cs

示例7: Should_map_the_existing_array_elements_over

            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]);
            }
开发者ID:GeertVL,项目名称:AutoMapper,代码行数:28,代码来源:DuplicateValuesBug.cs

示例8: GetCurrentPosition

 public IEnumerable<CurrentPosition> GetCurrentPosition()
 {
     var config = new MapperConfiguration(cfg => cfg.CreateMap<Position, CurrentPosition>());
     var mapper = config.CreateMapper();
     var result = new List<CurrentPosition>();
     var positions = _positionRepository.Get();
     foreach (var position in positions)
     {
         var current = mapper.Map<CurrentPosition>(position);
         if (current.CurrencyCode == "AUD")
         {
             current.CurrentPrice = _screenScrapper.GetYahooPrice($"{current.Key}.AX").Result;
         }
         else
         {
             current.CurrentPrice = _screenScrapper.GetYahooPrice(current.Key).Result / _screenScrapper.GetYahooPrice($"AUD{current.CurrencyCode}=X").Result;
         }
         //make the calculation
         current.TotalNow = current.Quantity * current.CurrentPrice;
         current.TotalWhenBought = current.Quantity * current.PriceWhenBought;
         current.DaysSinceBought = (int)(DateTime.Now - current.DateWhenBought).TotalDays;
         current.DifferenceMoney = current.TotalNow - current.TotalWhenBought;
         current.DifferencePercentage = (current.DifferenceMoney / current.TotalWhenBought) * 100;
         result.Add(current);
     }
     return result;
 }
开发者ID:ozcarzarate,项目名称:Asx,代码行数:27,代码来源:PositionService.cs

示例9: Should_map_source_properties

 public void Should_map_source_properties()
 {
     var config = new MapperConfiguration(cfg => { });
     dynamic destination = config.CreateMapper().Map<DynamicDictionary>(new Source());
     ((int)destination.Count).ShouldEqual(1);
     Assert.Equal(24, destination.Value);
 }
开发者ID:AutoMapper,项目名称:AutoMapper,代码行数:7,代码来源:DynamicMapperTests.cs

示例10: Example

            public void Example()
            {
                // Model
                var calendarEvent = new CalendarEvent
                    {
                        EventDate = new DateTime(2008, 12, 15, 20, 30, 0),
                        Title = "Company Holiday Party"
                    };

                var config = new MapperConfiguration(cfg =>
                {
                    // Configure AutoMapper
                    cfg.CreateMap<CalendarEvent, CalendarEventForm>()
                        .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date))
                        .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour))
                        .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute));
                });

                // Perform mapping
                var mapper = config.CreateMapper();
                CalendarEventForm form = mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);

                form.EventDate.ShouldEqual(new DateTime(2008, 12, 15));
                form.EventHour.ShouldEqual(20);
                form.EventMinute.ShouldEqual(30);
                form.Title.ShouldEqual("Company Holiday Party");
            }
开发者ID:GeertVL,项目名称:AutoMapper,代码行数:27,代码来源:Projection.cs

示例11: RegisterProfiles

        public static IMapper RegisterProfiles()
        {
            var config = new MapperConfiguration(
                cfg =>
                {
                    //Model para Dto
                    cfg.CreateMap<TarefaCadastroModel, TarefaDto>()
                        .ForMember(dto => dto.Usuario.Id,model => model.MapFrom(m => m.IdUsuario));

                    cfg.CreateMap<TarefaEdicaoModel, TarefaDto>()
                        .ForMember(dto => dto.Usuario.Id, model => model.MapFrom(m => m.IdUsuario));

                    cfg.CreateMap<TarefaExcluirModel, TarefaDto>()
                        .ForMember(dto => dto.Usuario.Id, model => model.MapFrom(m => m.IdUsuario));

                    cfg.CreateMap<TarefaEdicaoModel, TarefaDto>()
                        .ForMember(dto => dto.Usuario.Id, model => model.MapFrom(m => m.IdUsuario));

                    cfg.CreateMap<AutenticacaoModel, UsuarioDto>();

                    //Dto para Model
                    /*
                    cfg.CreateMap<Usuario, UsuarioDto>();
                    cfg.CreateMap<UsuarioDto, Usuario>();
                     */
                }
            );

            var mapper = config.CreateMapper();

            return mapper;
        }
开发者ID:gabrielsimas,项目名称:SistemasExemplo,代码行数:32,代码来源:AutoMapperConfig.cs

示例12: TodoListService

 public TodoListService(IUnitOfWork uow,ITodoListRepository todoListRepository)
 {
     _todoListRepository = todoListRepository;
     db = uow;
     var config = new MapperConfiguration(cfg => { cfg.CreateMap<TodoListEntity, TodoListDTO>(); });
     _mapper = config.CreateMapper();
 }
开发者ID:sokoloWladislav,项目名称:Wunderlist,代码行数:7,代码来源:TodoListService.cs

示例13: Should_map_source_properties

 public void Should_map_source_properties()
 {
     var config = new MapperConfiguration(cfg => { });
     _destination = config.CreateMapper().Map<DynamicDictionary>(new Destination {Foo = "Foo", Bar = "Bar"});
     Assert.Equal("Foo", _destination.Foo);
     Assert.Equal("Bar", _destination.Bar);
 }
开发者ID:284247028,项目名称:AutoMapper,代码行数:7,代码来源:DynamicMapperTests.cs

示例14: Should_map_properties_with_different_names

        public void Should_map_properties_with_different_names()
        {
            var config = new MapperConfiguration(c =>
            {
                c.ReplaceMemberName("Ä", "A");
                c.ReplaceMemberName("í", "i");
                c.ReplaceMemberName("Airlina", "Airline");
                c.CreateMap<Source, Destination>();
            });

            var source = new Source()
            {
                Value = 5,
                Ävíator = 3,
                SubAirlinaFlight = 4
            };

            //Mapper.AddMemberConvention().AddName<ReplaceName>(_ => _.AddReplace("A", "Ä").AddReplace("i", "í").AddReplace("Airline", "Airlina")).SetMemberInfo<FieldPropertyMemberInfo>();
            var mapper = config.CreateMapper();
            var destination = mapper.Map<Source, Destination>(source);

            Assert.AreEqual(source.Value, destination.Value);
            Assert.AreEqual(source.Ävíator, destination.Aviator);
            Assert.AreEqual(source.SubAirlinaFlight, destination.SubAirlineFlight);
        }
开发者ID:ouyh18,项目名称:LtePlatform,代码行数:25,代码来源:MemberNameReplacers.cs

示例15: Example

			public void Example()
			{
				var config = new MapperConfiguration(cfg =>
				{
					cfg.AddProfile<ViewModelProfile>();
					cfg.CreateMap<Order, OrderEditViewModel>();
				});

				var order = new Order {Amount = 50m};

				var listViewModel = config.CreateMapper().Map<Order, OrderListViewModel>(order);
				var editViewModel = config.CreateMapper().Map<Order, OrderEditViewModel>(order);

				listViewModel.Amount.ShouldEqual(order.Amount.ToString("c"));
				editViewModel.Amount.ShouldEqual("50");
			}
开发者ID:RahmanM,项目名称:AutoMapper,代码行数:16,代码来源:Profiles.cs


注:本文中的MapperConfiguration.CreateMapper方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。