我正在解决软件开发人员入学考试,我必须开发一个学生注册课程应用程序,并且在其中一个阶段需要编写一个映射器函数,将模型与他的 ModelDto 映射。我这样做了,但现在我必须按照 Omnio(干净架构)方法论软件开发的顺序进行重构。
这是主题模型:
public class Subject
{
public int? SubjectId {get; set; }
public string? Title {get; set; }
public int? Credits {get; set; }
public string registerAt? {get; set;}
}
公共课SubjectDto
public string? Title {get; set; }
public int? Credits {get; set; }
public string registerAt? {get; set;}
现在这是我确定的 Mapper 配置:
public class MapperConfig:Profile
{
public static MapperConfiguration InitializeAutoMapper()
{
//Provide all the Mapping Configuration
var config = new MapperConfiguration(cfg =>
{
//Configuring Subject and EmployeeDTO
cfg.CreateMap<Subject, SubjectDto>()
//Provide Mapping Configuration of FullName and Name Property
.ForMember(dest => dest.Title, act => act.MapFrom(src => src.Title))
//Provide Mapping Dept of FullName and Department Property
.ForMember(dest => dest.Credits, act => act.MapFrom(src => src.Credits));
//Any Other Mapping Configuration ....
});
return config;
}
}
这就是我在控制器中使用它的方式:
public async Task<IEnumerable<SubjectDto>> GetAllAsync(int id, CancellationToken cancellationToken = default)
{
var subjects = await _context.Subject.GetSubjectsAsync(id, cancellationToken);
if (subjects is null)
{
throw new SubjectNotFoundException(id);
}
var mapper = MapperConfig.InitializeAutoMapper();
var subjectDto = mapper.Map<SubjectDto>(subjects); #cause the error CS1061
}
它告诉我 MapperConfig 没有可扩展的 Map 方法。
如果有人可以帮助正确重构Mapper函数,我将非常感激。
调整你的配置类:
public class MapperConfig
{
public static Mapper InitializeAutoMapper()
{
//Provide all the Mapping Configuration
var config = new MapperConfiguration(cfg =>
{
//Configuring Subject and EmployeeDTO
cfg.CreateMap<Subject, SubjectDto>()
//Provide Mapping Configuration of FullName and Name Property
.ForMember(dest => dest.Title, act => act.MapFrom(src => src.Title))
//Provide Mapping Dept of FullName and Department Property
.ForMember(dest => dest.Credits, act => act.MapFrom(src => src.Credits));
//Any Other Mapping Configuration ....
});
var mapper = new Mapper(config);
return mapper;
}
}
不要忘记纠正你的模型:
public string registerAt? {get; set;}
到
public string? registerAt {get; set;}
最后,根据您的情况,为您要返回的列表制作地图:
var subjects = mapper.Map<IEnumerable<SubjectDto>>(subjects)
retunr subjects ;
希望对您有帮助