如何使用automapper进行映射?

时间:2018-03-07 17:05:53

标签: asp.net-mvc entity-framework automapper

我的应用程序中有一个Application模型:

public class Application
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public List<Guid> FunctionIds { get; set; }
}

底层Application db表具有以下结构:

Id - string
Name - string
Description - string 
ApplicationFunctions - ApplicationFunctions (FK)

我在发送没有FunctionId的模型时遇到以下错误:

{"\nUnmapped members were found. Review the types and members below.\nAdd a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type\nFor no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters

\nApplication -> Application (Destination member list)\r\nSecurityApi.Core.Models.Application -> 

SecurityApi.EntityFramework.Application (Destination member list)\r\n\r\nUnmapped properties:\r

\nApplicationFunctions\r\n"}

将FunctionIds映射到ApplicationFunctions的正确方法是什么?还有什么特殊的配置我需要允许FunctionIds的空值?

1 个答案:

答案 0 :(得分:0)

Automapper会自动映射具有相同名称和类型的成员,但如果它们不匹配,则必须告知Automapper如何执行此操作。首先,创建配置类:

public static class AutoMapperConfig
{
    public static void RegisterMappings()
    {
        AutoMapper.Mapper.CreateMap<Application, Core.Models.Application>().ForMember(
        dest => dest.FunctionIds,
        opt => opt.MapFrom(src => src.ApplicationFunctions);
        //Map other members and classes
    )
  }
}

然后,在Global.asax.cs中,初始化配置:

protected void Application_Start()
{
    AutoMapperConfig.RegisterMappings();
}