使用AutoMapper 6.1.1创建地图

时间:2017-11-03 09:03:35

标签: c# entity-framework automapper

我有两个实体EF类别Region和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
}

我想将这些实体映射到相应的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>() 我该如何解决?

1 个答案:

答案 0 :(得分:1)

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