我是。net的新手,所以我决定使用。net Core,而不是学习“老方法”。我在这里找到了一篇关于为。net Core设置AutoMapper的详细文章,但是对于新手来说还有更简单的操作指南吗?
当前回答
添加到Arve Systad提到的测试中。如果你像我一样,想要维护utz解决方案中提供的继承结构,你可以像这样设置MapperConfiguration:
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(mappingProfile);
});
var mapper = new Mapper(config);
我在NUnit中做过这个。
其他回答
我想明白了!细节如下:
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! } }
services.AddAutoMapper ();对我没用。(我用的是Asp。Net Core 2.0)
配置如下
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientCustomer, Models.Customer>();
});
初始化映射器 IMapper mapper = config.CreateMapper();
并将mapper对象作为单例添加到服务中 services.AddSingleton(映射);
这样我就可以添加DI到控制器
private IMapper autoMapper = null;
public VerifyController(IMapper mapper)
{
autoMapper = mapper;
}
我在我的动作方法中使用了如下
ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);
让我们来看看如何将Auto mapper添加到。net Core应用程序中。
步骤:1 第一步是安装相应的NuGet包:
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
一步:2
安装所需的包后,下一步是配置服务。让我们在Startup.cs类中执行:
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(Startup));
services.AddControllersWithViews();
}
一步:3
让我们开始使用,我们有一个名为User的域对象:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Address { get; set; }
}
在UI层,我们将有一个视图模型来显示用户信息:
public class UserViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
一步:4
组织映射配置的一个好方法是使用Profiles。我们需要创建从Profile类继承的类,并将配置放在构造函数中:
public UserProfile()
{
CreateMap<User, UserViewModel>();
}
一步:5
现在,让我们定义一个Controller并使用我们刚刚添加的Auto-Mapping功能:
public class UserController : Controller
{
private readonly IMapper _mapper;
public UserController(IMapper mapper)
{
_mapper = mapper;
}
public IActionResult Index()
{
// Populate the user details from DB
var user = GetUserDetails();
UserViewModel userViewModel = _mapper.Map<UserViewModel>(user);
return View(userViewModel);
}
}
首先,我们将映射器对象注入到控制器中。然后,我们调用Map()方法,它将User对象映射到UserViewModel对象。此外,请注意我们用于本地数据存储的本地方法GetUserDetails。 您可以在我们的源代码中找到它的实现。
对于使用。net 7的AutoMapper 11.0.1,我开始得到这个异常:
System.ArgumentException: 'GenericArguments[0], 'System.DateTime', on 'T MaxInteger[T](System.Collections.Generic.IEnumerable`1[T])' violates the constraint of type 'T'.'
Inner Exception
VerificationException: Method System.Linq.Enumerable.MaxInteger: type argument 'System.DateTime' violates the constraint of type parameter 'T'.
看这个问题:
系统。DateTime on 'T MaxInteger[T](System.Collections.Generic.IEnumerable ' 1[T])'违反了。net 7使用AutoMapper 11.0.1的T类型约束
这意味着我不能再使用services.AddAutoMapper(typeof(MappingProfile).Assembly);无一例外。
对于AutoMapper.Extensions.Microsoft.DependencyInjection我这样解决它:
services.AddAutoMapper(cfg => cfg.Internal().MethodMappingEnabled = false, typeof(MappingProfile).Assembly);
对于Blazor WebAssembly客户端,解决方案是这样的:
var mapperConfig = new MapperConfiguration(mc =>
{
//Needed for https://github.com/AutoMapper/AutoMapper/issues/3988
mc.Internal().MethodMappingEnabled = false;
mc.AddProfile(new MappingProfile());
});
//mapperConfig.AssertConfigurationIsValid();
IMapper mapper = mapperConfig.CreateMapper();
builder.Services.AddSingleton(mapper);
Asp。Net Core 2.2与AutoMapper.Extensions.Microsoft.DependencyInjection。
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Domain, DomainDto>();
}
}
在Startup.cs
services.AddAutoMapper(typeof(List.Handler));
推荐文章
- 在c#中从URI字符串获取文件名
- 检查SqlDataReader对象中的列名
- 如何将类标记为已弃用?
- c# 8支持。net框架吗?
- 什么是Kestrel (vs IIS / Express)
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- 组合框:向项目添加文本和值(无绑定源)
- AutoMapper:“忽略剩下的?”
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间