简体   繁体   中英

Create Map using AutoMapper 6.1.1

I have two entity EF classes Region and Country.

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
}

I want to map these entities to corresponding 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; }
}

However in AutoMapper 6.1.1 Mapper does not contain definition for CreateMap. Mapper.CreateMap<Regin, RegionViewModel>() How can I solve it?

You can create a class, to define your mapping profile:

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

Then in your application startup, initilize automapper using this profile, as an example, if you are using a console application, you can put the initialization in you Main method:

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

Or if you are using an Asp.Net MVC application, you can put the initialization in Application_Start() in Global.asax

var config = new MapperConfiguration(cfg => cfg.CreateMap<RegionViewModel, Region>());   
var mapper = config.CreateMapper();
Region target = mapper.Map<Region>(source as RegionViewModel);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM