我是。net的新手,所以我决定使用。net Core,而不是学习“老方法”。我在这里找到了一篇关于为。net Core设置AutoMapper的详细文章,但是对于新手来说还有更简单的操作指南吗?
当前回答
在最新版本的asp.net core中,你应该使用以下初始化:
services.AddAutoMapper(typeof(YourMappingProfileClass));
其他回答
我想明白了!细节如下:
Add the main AutoMapper Package to your solution via NuGet. Add the AutoMapper Dependency Injection Package to your solution via NuGet. Create a new class for a mapping profile. (I made a class in the main solution directory called MappingProfile.cs and add the following code.) I'll use a User and UserDto object as an example. public class MappingProfile : Profile { public MappingProfile() { // Add as many of these lines as you need to map your objects CreateMap<User, UserDto>(); CreateMap<UserDto, User>(); } } Then add the AutoMapperConfiguration in the Startup.cs as shown below: public void ConfigureServices(IServiceCollection services) { // .... Ignore code before this // Auto Mapper Configurations var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); services.AddMvc(); } To invoke the mapped object in code, do something like the following: public class UserController : Controller { // Create a field to store the mapper object private readonly IMapper _mapper; // Assign the object in the constructor for dependency injection public UserController(IMapper mapper) { _mapper = mapper; } public async Task<IActionResult> Edit(string id) { // Instantiate source object // (Get it from the database or whatever your code calls for) var user = await _context.Users .SingleOrDefaultAsync(u => u.Id == id); // Instantiate the mapped data transfer object // using the mapper you stored in the private field. // The type of the source object is the first type argument // and the type of the destination is the second. // Pass the source object you just instantiated above // as the argument to the _mapper.Map<>() method. var model = _mapper.Map<UserDto>(user); // .... Do whatever you want after that! } }
对于自动映射器 9.0.0:
public static IEnumerable<Type> GetAutoMapperProfilesFromAllAssemblies()
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var aType in assembly.GetTypes())
{
if (aType.IsClass && !aType.IsAbstract && aType.IsSubclassOf(typeof(Profile)))
yield return aType;
}
}
}
MapperProfile:
public class OrganizationProfile : Profile
{
public OrganizationProfile()
{
CreateMap<Foo, FooDto>();
// Use CreateMap... Etc.. here (Profile methods are the same as configuration methods)
}
}
在你的初创公司:
services.AddAutoMapper(GetAutoMapperProfilesFromAllAssemblies()
.ToArray());
在控制器或服务中: 注入映射器:
private readonly IMapper _mapper;
用法:
var obj = _mapper.Map<TDest>(sourceObject);
theutz的回答很好,我只想补充一点:
如果你让你的映射配置文件继承自MapperConfigurationExpression而不是profile,你可以非常简单地添加一个测试来验证你的映射设置,这总是很方便:
[Fact]
public void MappingProfile_VerifyMappings()
{
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(mappingProfile);
var mapper = new Mapper(config);
(mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
在我的Startup.cs (Core 2.2, Automapper 8.1.1)
services.AddAutoMapper(new Type[] { typeof(DAL.MapperProfile) });
在我的数据访问项目中
namespace DAL
{
public class MapperProfile : Profile
{
// place holder for AddAutoMapper (to bring in the DAL assembly)
}
}
在模型定义中
namespace DAL.Models
{
public class PositionProfile : Profile
{
public PositionProfile()
{
CreateMap<Position, PositionDto_v1>();
}
}
public class Position
{
...
}
我喜欢很多答案,尤其是@saineshwar的答案。我使用的是。net Core 3.0和AutoMapper 9.0,所以我觉得是时候更新答案了。
对我有用的是在Startup.ConfigureServices(…)中以这样的方式注册服务:
services.AddAutoMapper(cfg => cfg.AddProfile<MappingProfile>(),
AppDomain.CurrentDomain.GetAssemblies());
我认为@saineshwar的其余答案保持完美。但如果有人感兴趣,我的控制器代码是:
[HttpGet("{id}")]
public async Task<ActionResult> GetIic(int id)
{
// _context is a DB provider
var Iic = await _context.Find(id).ConfigureAwait(false);
if (Iic == null)
{
return NotFound();
}
var map = _mapper.Map<IicVM>(Iic);
return Ok(map);
}
我的映射类:
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Iic, IicVM>()
.ForMember(dest => dest.DepartmentName, o => o.MapFrom(src => src.Department.Name))
.ForMember(dest => dest.PortfolioTypeName, o => o.MapFrom(src => src.PortfolioType.Name));
//.ReverseMap();
}
}
-----编辑-----
在阅读了Lucian Bargaoanu评论中的文档链接后,我认为最好稍微改变一下这个答案。
无参数services.AddAutoMapper()(具有@saineshwar答案)不再工作(至少对我来说)。但是如果你使用NuGet程序集AutoMapper.Extensions.Microsoft。DependencyInjection,框架能够检查所有扩展AutoMapper的类。配置文件(像我的,MappingProfile)。
因此,在我的例子中,类属于同一个正在执行的程序集,服务注册可以缩短为services.AddAutoMapper(System.Reflection.Assembly.GetExecutingAssembly()); (一种更优雅的方法是使用这种编码的无参数扩展)。
谢谢,卢西恩!
推荐文章
- 随机字符串生成器返回相同的字符串
- 为什么Func<T,bool>而不是Predicate<T>?
- .NET中的Map和Reduce
- 我如何能使一个组合框不可编辑的。net ?
- .NET反射的成本有多高?
- 实体框架回滚并移除不良迁移
- 将流转换为字符串并返回
- 在c#中检查字符串是否只包含数字的最快方法
- IEquatable和重写Object.Equals()之间的区别是什么?
- 创建一个堆栈大小为默认值50倍的线程有什么危险?
- 转换JSON字符串到JSON对象c#
- 显示两个datetime值之间的小时差值
- 如何设置enum为空
- 选择Enum类型的默认值而无需更改值
- 我如何设置在一个组合框中选择的项目,以匹配我的字符串使用c# ?