我正在尝试使用实体框架将 Automapper 包含到项目中,这是我的 DTO 类:
public class FunctionDto
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string Comment { get; set; }
public DateTime? ExaminationDate { get; set; }
public string Place { get; set; }
}
域类代码优先:
public class Function
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string Comment { get; set; }
public DateTime? ExaminationDate { get; set; }
public string Place { get; set; }
public virtual List<Employee> Employees { get; set; }
}
自动映射器配置:
public static class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(config => config.AddProfile<FunctionProfile>());
}
}
public class FunctionProfile : Profile
{
protected override void Configure()
{
CreateMap<Function, FunctionDto>()
.ForMember(dto => dto.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dto => dto.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(dto => dto.Comment, opt => opt.MapFrom(src => src.Comment))
.ForMember(dto => dto.StartDate, opt => opt.MapFrom(src => src.StartDate))
.ForMember(dto => dto.EndDate, opt => opt.MapFrom(src => src.EndDate))
.ForMember(dto => dto.ExaminationDate, opt => opt.MapFrom(src => src.ExaminationDate))
.ForMember(dto => dto.Place, opt => opt.MapFrom(src => src.Place));
}
}
然后在 WebApi 中使用:
var functionDtos = functions
.AsQueryable()
.OrderBy(sort)
.Skip(start)
.Take(count)
.ToList()
.Select(Mapper.Map<FunctionDto>);
当然我已经在全球注册了:
AutoMapperConfiguration.Configure();
但我得到了例外:
缺少类型映射配置或不支持的映射
上面的代码有什么问题?