我是。net的新手,所以我决定使用。net Core,而不是学习“老方法”。我在这里找到了一篇关于为。net Core设置AutoMapper的详细文章,但是对于新手来说还有更简单的操作指南吗?
当前回答
让我们来看看如何将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 Core 3.x
创建MappingProfile.cs类并使用Maps填充构造函数(我计划使用一个类来保存所有映射)
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Source, Dest>().ReverseMap();
}
}
在Startup.cs中,添加下面的内容以添加到DI(程序集参数用于保存映射配置的类,在我的例子中,它是MappingProfile类)。
//add automapper DI
services.AddAutoMapper(typeof(MappingProfile));
在Controller中,像使用其他DI对象一样使用它
[Route("api/[controller]")]
[ApiController]
public class AnyController : ControllerBase
{
private readonly IMapper _mapper;
public AnyController(IMapper mapper)
{
_mapper = mapper;
}
public IActionResult Get(int id)
{
var entity = repository.Get(id);
var dto = _mapper.Map<Dest>(entity);
return Ok(dto);
}
}
ASP。NET Core(使用2.0+和3.0测试),如果你喜欢阅读源文档: https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/README.md
否则,遵循以下4个步骤即可:
从nuget安装AutoMapper.Extensions.Microsoft.DependancyInjection。 只需添加一些概要文件类。 然后将以下内容添加到你的startup.cs类中。 services.AddAutoMapper (OneOfYourProfileClassNamesHere) 然后简单地在你的控制器或任何你需要它的地方注入IMapper:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper){
_mapper = mapper;
}
如果你想使用ProjectTo,现在很简单:
var customers = await dbContext.Customers.ProjectTo<CustomerDto>(_mapper.ConfigurationProvider).ToListAsync()
我想扩展@theutz的答案-即这一行:
// services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature.
AutoMapper.Extensions.Microsoft.DependencyInjection版本3.2.0中有一个错误(可能)。(我使用的是。net Core 2.0)
这个问题在这个GitHub问题中解决。如果你继承AutoMapper的Profile类存在于你的Startup类所在的程序集之外,如果你的AutoMapper注入是这样的,它们可能不会被注册:
services.AddAutoMapper();
除非您显式指定要搜索AutoMapper概要文件的程序集。
在你的初创公司中也可以这样做。ConfigureServices:
services.AddAutoMapper(<assembies> or <type_in_assemblies>);
其中"assemblies"和"type_in_assemblies"指向应用程序中指定Profile类的程序集。例句:
services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));
我认为(我强调这个词)由于以下无参数重载的实现(来自GitHub的源代码):
public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}
我们依赖于CLR已经包含AutoMapper配置文件的JITed程序集,这可能是真的,也可能不是真的,因为它们只在需要时被jit(更多细节在这个StackOverflow问题中)。
使用ASP使用AutoMapper。净的核心。
步骤1。从NuGet包中安装AutoMapper.Extensions.Microsoft.DependencyInjection。
步骤2。在“解决方案”中创建一个文件夹以保存名称为“Mappings”的映射。
步骤3。添加映射文件夹后,我们添加了一个名为“MappingProfile”的类,这个名称可以是唯一的,很好理解。
在本课程中,我们将维护所有映射。
步骤4。在启动“ConfigureServices”时初始化映射器
在启动类,我们需要初始化配置文件,我们已经创建和注册AutoMapper服务。
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
显示ConfigureServices方法的代码片段,其中我们需要初始化和注册AutoMapper。
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Start Registering and Initializing AutoMapper
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
// End Registering and Initializing AutoMapper
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}}
第5步。得到的输出。
为了获得映射结果,我们需要调用AutoMapper.Mapper.Map并传递正确的目的地和源。
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
在最新版本的asp.net core中,你应该使用以下初始化:
services.AddAutoMapper(typeof(YourMappingProfileClass));
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- 在哪里放置AutoMapper.CreateMaps?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- .NET核心MVC页面更改后不刷新