【问题标题】:Create Map using AutoMapper 6.1.1使用 AutoMapper 6.1.1 创建地图
【发布时间】:2017-11-03 09:03:35
【问题描述】:

我有两个实体 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
}

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

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&lt;Regin, RegionViewModel&gt;() 我该如何解决?

【问题讨论】:

    标签: c# entity-framework automapper


    【解决方案1】:

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

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

    然后在你的应用程序启动中,使用这个配置文件初始化automapper,例如,如果你使用的是控制台应用程序,你可以把初始化放在你的Main方法中:

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

    或者如果您使用的是 Asp.Net MVC 应用程序,您可以将初始化放在 Global.asax

    中的 Application_Start()

    【讨论】:

    • 不知道为什么这不是官方文档中的#1 项目...谢谢!
    【解决方案2】:
    var config = new MapperConfiguration(cfg => cfg.CreateMap<RegionViewModel, Region>());   
    var mapper = config.CreateMapper();
    Region target = mapper.Map<Region>(source as RegionViewModel);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多