代码之家  ›  专栏  ›  技术社区  ›  maciejka

使用AutoMapper 6.1.1创建地图

  •  1
  • maciejka  · 技术社区  · 7 年前

    public class Region
    {
        public int Id { get; set; } 
        public string Name { get; set; }
        public virtual ICollection<Country> Countries { get; set; } 
    }
    
    public class Country
    {
        public int Id { get; set; } 
        public string Name { get; set; }
        public int RegionId { get; set; } // FK
    }
    

    我想将这些实体映射到相应的ViewModels。

    public class RegionViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<int> Countries { get; set; }
    }
    public class CountryViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    然而,在AutoMapper 6.1.1中,Mapper不包含CreateMap的定义。 Mapper.CreateMap<Regin, RegionViewModel>()

    2 回复  |  直到 7 年前
        1
  •  2
  •   Hooman Bahreini    6 年前

    您可以创建一个类来定义映射配置文件:

    public class MyMappingProfile : Profile
    {
        public MyMappingProfile()
        {
            // define your mapping here, for example:
            CreateMap<RegionViewModel, Region>().ReverseMap();
            CreateMap<CountryViewModel, Country>().ReverseMap();
        }
    }
    

    static void Main(string[] args)
    {
        Mapper.Initialize(c => c.AddProfile<MyMappingProfile>()); 
        // other initialization...
    

    或者,如果您使用的是Asp。Net MVC应用程序,您可以将初始化放入 应用程序启动() 全球的asax公司

        2
  •  1
  •   Darko Maric Programer    7 年前
    var config = new MapperConfiguration(cfg => cfg.CreateMap<RegionViewModel, Region>());   
    var mapper = config.CreateMapper();
    Region target = mapper.Map<Region>(source as RegionViewModel);