【发布时间】:2020-11-01 19:49:15
【问题描述】:
我在我的 Web API 应用程序中配置了 AutoMapper 'AutoMapper.Extensions.Microsoft.DependencyInjection 版本 7.0',如下所示;我收到 Missing Type Map 配置映射错误。
启动
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<SupplierContext>(options =>
options.UseInMemoryDatabase(databaseName: "MyDatabase"));
services.AddTransient<IAppService, AppService>();
var profiles = from type in typeof(Startup).Assembly.GetTypes()
where typeof(Profile).IsAssignableFrom(type)
select (Profile)Activator.CreateInstance(type);
var mapConfig = new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
var mapper = mapConfig.CreateMapper();
services.AddSingleton(mapper);
}
我在文件夹下的主项目 API 中创建了一个配置文件
简介
public UserProfile()
{
CreateMap<User, UserDataView>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(dataModel => dataModel.Id))
.ForMember(dest => dest.Title, opt => opt.MapFrom(dataModel => dataModel.Title))
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(dataModel => dataModel.FirstName))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(dataModel => dataModel.LastName))
.ForMember(dest => dest.ActivationDate, opt => opt.MapFrom(dataModel => dataModel.ActivationDate));
//CreateMap<User, UserDataView>()
// .ReverseMap();
}
用户类
public class User
{
public Guid Id { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime ActivationDate { get; set; }
}
当我尝试将模型数据映射到 Dto 时,出现缺少类型映射配置错误
错误
Missing type map configuration or unsupported mapping.
Mapping types:
Task`1 -> List`1
System.Threading.Tasks.Task`1[[System.Collections.Generic.List`1[[MyApp.Model.User.User, MyApp.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea70000]] -> System.Collections.Generic.List`1[[MyApp.Model.DTOs.UserDataView, MyApp.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
自动映射
var UserDataModel = (from user in _context.Users
join email in _context.Emails on user.Id equals email.userId into se
join phone in _context.Phones on user.Id equals phone.userId into sp
select new User
{
Id = user.Id,
Title = user.Title,
FirstName = user.FirstName,
LastName = user.LastName,
ActivationDate = user.ActivationDate,
}).ToListAsync();
var dataResult = _mapper.Map<List<UserDataView>>(UserDataModel);
【问题讨论】:
标签: automapper asp.net-core-2.2 webapi