How to setup Automapper in ASP.NET Core
I'm relatively new at .NET, and I decided to tackle .NET Core instead of learning the "old ways". I found a detailed article about setting up AutoMapper for .NET Core here, but is there a more simple walkthrough for a newbie?
c# asp.net-core automapper
add a comment |
I'm relatively new at .NET, and I decided to tackle .NET Core instead of learning the "old ways". I found a detailed article about setting up AutoMapper for .NET Core here, but is there a more simple walkthrough for a newbie?
c# asp.net-core automapper
4
See dotnetcoretutorials.com/2017/09/23/…
– Michael Freidgeim
Dec 8 '17 at 6:15
For newer versions of core (>v1) check out @Saineshwar's answer stackoverflow.com/a/53455699/833878
– Robbie
Feb 16 at 21:01
add a comment |
I'm relatively new at .NET, and I decided to tackle .NET Core instead of learning the "old ways". I found a detailed article about setting up AutoMapper for .NET Core here, but is there a more simple walkthrough for a newbie?
c# asp.net-core automapper
I'm relatively new at .NET, and I decided to tackle .NET Core instead of learning the "old ways". I found a detailed article about setting up AutoMapper for .NET Core here, but is there a more simple walkthrough for a newbie?
c# asp.net-core automapper
c# asp.net-core automapper
edited Jul 30 '17 at 9:17
Set
24.6k1080100
24.6k1080100
asked Oct 27 '16 at 2:34
theutztheutz
4,98931316
4,98931316
4
See dotnetcoretutorials.com/2017/09/23/…
– Michael Freidgeim
Dec 8 '17 at 6:15
For newer versions of core (>v1) check out @Saineshwar's answer stackoverflow.com/a/53455699/833878
– Robbie
Feb 16 at 21:01
add a comment |
4
See dotnetcoretutorials.com/2017/09/23/…
– Michael Freidgeim
Dec 8 '17 at 6:15
For newer versions of core (>v1) check out @Saineshwar's answer stackoverflow.com/a/53455699/833878
– Robbie
Feb 16 at 21:01
4
4
See dotnetcoretutorials.com/2017/09/23/…
– Michael Freidgeim
Dec 8 '17 at 6:15
See dotnetcoretutorials.com/2017/09/23/…
– Michael Freidgeim
Dec 8 '17 at 6:15
For newer versions of core (>v1) check out @Saineshwar's answer stackoverflow.com/a/53455699/833878
– Robbie
Feb 16 at 21:01
For newer versions of core (>v1) check out @Saineshwar's answer stackoverflow.com/a/53455699/833878
– Robbie
Feb 16 at 21:01
add a comment |
9 Answers
9
active
oldest
votes
I figured it out! Here's the details:
- 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 aUser
andUserDto
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 mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.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!
}
}
I hope this helps someone starting fresh with ASP.NET Core! I welcome any feedback or criticisms as I'm still new to the .NET world!
2
You should include the constructor for MappingProfile to contain the calls to CreateMap
– Brian Seim at EvoDynamic LLC
Nov 2 '16 at 1:37
3
The detailed article linked, lostechies.com/jimmybogard/2016/07/20/…, explains howProfile
classes are located
– Kieren Johnstone
Dec 22 '16 at 8:25
13
@theutz You can merge those two CreateMap lines with a .ReverseMap() at the end of, well, either. Maybe comment it, but I find it more intuitive.
– Astravagrant
Mar 31 '17 at 12:40
4
It might be helpful on Step 3 to mention adding a "using AutoMapper;" at the top so that the extension method is imported.
– Rocklan
May 30 '17 at 1:47
5
This worked fine with .net core 1.1, not anymore once I upgraded to .net core 2.0. I think, I need to explicitly specify the logic profile class assembly. Still researching how to accomplish that. Update: Ah the answer resides on your comment, I have to pass the typeof class which is my profile. // services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature
– Esen
Sep 23 '17 at 16:35
|
show 9 more comments
theutz' answer here is very good, I just want to add this:
If you let your mapping profile inherit from MapperConfigurationExpression
instead of Profile
, you can very simply add a test to verify your mapping setup, which is always handy:
[Fact]
public void MappingProfile_VerifyMappings()
{
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(mappingProfile);
var mapper = new Mapper(config);
(mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
I am getting one error : "AutoMapper Extension Dependency injection is incompatible with asp.net core 1.1 ". Please help!
– Rohit Arora
Aug 31 '17 at 4:38
It seems the definition of "verify" is up for debate. This blows up when certain properties are ommitted by design to prevent mapping.
– Jeremy Holovacs
Mar 21 '18 at 19:36
1
If you don’t want a property mapped, set it up with .Ignore(). That way, it forces you to actively think about handling each case - making sure you don’t miss out on stuff when changes are being made. Super practical, actually. So yes, the verify-test is a larger safety net than many people realise. It’s not foolproof, but it takes care of the first 90%.
– Arve Systad
Mar 23 '18 at 5:13
add a comment |
I want to extend @theutz's answers - namely this line :
// services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature.
There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)
This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:
services.AddAutoMapper();
unless you explicitly specify which assemblies to search AutoMapper profiles for.
It can be done like this in your Startup.ConfigureServices:
services.AddAutoMapper(<assembies> or <type_in_assemblies>);
where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:
services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));
I suppose (and I put emphasis on this word) that due to following implementaion of parameterless overaload (source code from GitHub) :
public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}
we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more deatils in this StackOverflow question).
add a comment |
Step To Use AutoMapper with ASP.NET Core.
Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.
Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".
Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.
In this class, we are going to Maintain all Mappings.
Step 4. Initializing Mapper in Startup "ConfigureServices"
In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
Code Snippet to show ConfigureServices Method where we need to Initialize and Register 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);
}}
Step 5. Get Output.
To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
add a comment |
I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.
First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.
public class UserProfile : Profile, IProfile
{
public UserProfile()
{
CreateMap<User, UserModel>();
CreateMap<UserModel, User>();
}
}
Now create a separate class e.g Mappings
public class Mappings
{
public static void RegisterMappings()
{
var all =
Assembly
.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.SelectMany(x => x.DefinedTypes)
.Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
var t = ti.AsType();
if (t.Equals(typeof(IProfile)))
{
Mapper.Initialize(cfg =>
{
cfg.AddProfiles(t); // Initialise each Profile classe
});
}
}
}
}
Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application
loading.
Mappings.RegisterMappings();
You can just create a subclass from profile class, and when program is running services.AddAutoMapper(); line of codes The automapper automatically knows them.
– isaeid
Oct 1 '17 at 13:49
I don't think this is necessary if you use AutoMapper.Extensions.Microsoft.DependancyInjection which is available in nuget.
– Greg Gum
Aug 18 '18 at 10:43
add a comment |
services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)
After configuring as below
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientCustomer, Models.Customer>();
});
initialize the mapper
IMapper mapper = config.CreateMapper();
and add the mapper object to services as a singleton
services.AddSingleton(mapper);
this way I am able to add a DI to controller
private IMapper autoMapper = null;
public VerifyController(IMapper mapper)
{
autoMapper = mapper;
}
and I have used as below in my action methods
ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);
add a comment |
For ASP.NET Core, the following is direct from Automapper and is 1 line in your startup class:
https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/README.md
Simply add some profile classes. Then add below to your startup.cs class.
services.AddAutoMapper(OneOfYourProfileClassNamesHereSoItCanFindYourProfileAssembly)
Then simply Inject IMapper in your controllers or wherever you need it:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper)
=> _mapper = mapper;
// use _mapper.Map to map
}
And if you want to use ProjectTo its now simply:
var customers = await dbContext.Customers.ProjectTo<CustomerDto>(_mapper.ConfigurationProvider).ToListAsync()
add a comment |
about theutz answer ,
there is no need to specify the IMapper mapper parrameter at the controllers constructor.
you can use the Mapper as it is a static member at any place of the code.
public class UserController : Controller {
public someMethod()
{
Mapper.Map<User, UserDto>(user);
}
}
8
But statics are a bit anti-testable, no?
– Scott Fraley
May 17 '17 at 17:40
2
Yep. This will work in many cases, but if you have no configured mapping when invoking this method in a test, It'll throw an exception (and thus failing the test for the wrong reason). With an injectedIMapper
you can mock that and, for example, just make it return null if it's irrelevant for the given test.
– Arve Systad
May 29 '17 at 20:48
add a comment |
To add onto what Arve Systad mentioned for testing. If for whatever reason you're like me and want to maintain the inheritance structure provided in theutz solution, you can set up the MapperConfiguration like so:
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(mappingProfile);
});
var mapper = new Mapper(config);
I did this in NUnit.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40275195%2fhow-to-setup-automapper-in-asp-net-core%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
I figured it out! Here's the details:
- 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 aUser
andUserDto
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 mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.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!
}
}
I hope this helps someone starting fresh with ASP.NET Core! I welcome any feedback or criticisms as I'm still new to the .NET world!
2
You should include the constructor for MappingProfile to contain the calls to CreateMap
– Brian Seim at EvoDynamic LLC
Nov 2 '16 at 1:37
3
The detailed article linked, lostechies.com/jimmybogard/2016/07/20/…, explains howProfile
classes are located
– Kieren Johnstone
Dec 22 '16 at 8:25
13
@theutz You can merge those two CreateMap lines with a .ReverseMap() at the end of, well, either. Maybe comment it, but I find it more intuitive.
– Astravagrant
Mar 31 '17 at 12:40
4
It might be helpful on Step 3 to mention adding a "using AutoMapper;" at the top so that the extension method is imported.
– Rocklan
May 30 '17 at 1:47
5
This worked fine with .net core 1.1, not anymore once I upgraded to .net core 2.0. I think, I need to explicitly specify the logic profile class assembly. Still researching how to accomplish that. Update: Ah the answer resides on your comment, I have to pass the typeof class which is my profile. // services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature
– Esen
Sep 23 '17 at 16:35
|
show 9 more comments
I figured it out! Here's the details:
- 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 aUser
andUserDto
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 mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.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!
}
}
I hope this helps someone starting fresh with ASP.NET Core! I welcome any feedback or criticisms as I'm still new to the .NET world!
2
You should include the constructor for MappingProfile to contain the calls to CreateMap
– Brian Seim at EvoDynamic LLC
Nov 2 '16 at 1:37
3
The detailed article linked, lostechies.com/jimmybogard/2016/07/20/…, explains howProfile
classes are located
– Kieren Johnstone
Dec 22 '16 at 8:25
13
@theutz You can merge those two CreateMap lines with a .ReverseMap() at the end of, well, either. Maybe comment it, but I find it more intuitive.
– Astravagrant
Mar 31 '17 at 12:40
4
It might be helpful on Step 3 to mention adding a "using AutoMapper;" at the top so that the extension method is imported.
– Rocklan
May 30 '17 at 1:47
5
This worked fine with .net core 1.1, not anymore once I upgraded to .net core 2.0. I think, I need to explicitly specify the logic profile class assembly. Still researching how to accomplish that. Update: Ah the answer resides on your comment, I have to pass the typeof class which is my profile. // services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature
– Esen
Sep 23 '17 at 16:35
|
show 9 more comments
I figured it out! Here's the details:
- 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 aUser
andUserDto
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 mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.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!
}
}
I hope this helps someone starting fresh with ASP.NET Core! I welcome any feedback or criticisms as I'm still new to the .NET world!
I figured it out! Here's the details:
- 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 aUser
andUserDto
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 mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.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!
}
}
I hope this helps someone starting fresh with ASP.NET Core! I welcome any feedback or criticisms as I'm still new to the .NET world!
edited Sep 24 '18 at 9:57
TanvirArjel
8,46932046
8,46932046
answered Oct 27 '16 at 2:34
theutztheutz
4,98931316
4,98931316
2
You should include the constructor for MappingProfile to contain the calls to CreateMap
– Brian Seim at EvoDynamic LLC
Nov 2 '16 at 1:37
3
The detailed article linked, lostechies.com/jimmybogard/2016/07/20/…, explains howProfile
classes are located
– Kieren Johnstone
Dec 22 '16 at 8:25
13
@theutz You can merge those two CreateMap lines with a .ReverseMap() at the end of, well, either. Maybe comment it, but I find it more intuitive.
– Astravagrant
Mar 31 '17 at 12:40
4
It might be helpful on Step 3 to mention adding a "using AutoMapper;" at the top so that the extension method is imported.
– Rocklan
May 30 '17 at 1:47
5
This worked fine with .net core 1.1, not anymore once I upgraded to .net core 2.0. I think, I need to explicitly specify the logic profile class assembly. Still researching how to accomplish that. Update: Ah the answer resides on your comment, I have to pass the typeof class which is my profile. // services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature
– Esen
Sep 23 '17 at 16:35
|
show 9 more comments
2
You should include the constructor for MappingProfile to contain the calls to CreateMap
– Brian Seim at EvoDynamic LLC
Nov 2 '16 at 1:37
3
The detailed article linked, lostechies.com/jimmybogard/2016/07/20/…, explains howProfile
classes are located
– Kieren Johnstone
Dec 22 '16 at 8:25
13
@theutz You can merge those two CreateMap lines with a .ReverseMap() at the end of, well, either. Maybe comment it, but I find it more intuitive.
– Astravagrant
Mar 31 '17 at 12:40
4
It might be helpful on Step 3 to mention adding a "using AutoMapper;" at the top so that the extension method is imported.
– Rocklan
May 30 '17 at 1:47
5
This worked fine with .net core 1.1, not anymore once I upgraded to .net core 2.0. I think, I need to explicitly specify the logic profile class assembly. Still researching how to accomplish that. Update: Ah the answer resides on your comment, I have to pass the typeof class which is my profile. // services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature
– Esen
Sep 23 '17 at 16:35
2
2
You should include the constructor for MappingProfile to contain the calls to CreateMap
– Brian Seim at EvoDynamic LLC
Nov 2 '16 at 1:37
You should include the constructor for MappingProfile to contain the calls to CreateMap
– Brian Seim at EvoDynamic LLC
Nov 2 '16 at 1:37
3
3
The detailed article linked, lostechies.com/jimmybogard/2016/07/20/…, explains how
Profile
classes are located– Kieren Johnstone
Dec 22 '16 at 8:25
The detailed article linked, lostechies.com/jimmybogard/2016/07/20/…, explains how
Profile
classes are located– Kieren Johnstone
Dec 22 '16 at 8:25
13
13
@theutz You can merge those two CreateMap lines with a .ReverseMap() at the end of, well, either. Maybe comment it, but I find it more intuitive.
– Astravagrant
Mar 31 '17 at 12:40
@theutz You can merge those two CreateMap lines with a .ReverseMap() at the end of, well, either. Maybe comment it, but I find it more intuitive.
– Astravagrant
Mar 31 '17 at 12:40
4
4
It might be helpful on Step 3 to mention adding a "using AutoMapper;" at the top so that the extension method is imported.
– Rocklan
May 30 '17 at 1:47
It might be helpful on Step 3 to mention adding a "using AutoMapper;" at the top so that the extension method is imported.
– Rocklan
May 30 '17 at 1:47
5
5
This worked fine with .net core 1.1, not anymore once I upgraded to .net core 2.0. I think, I need to explicitly specify the logic profile class assembly. Still researching how to accomplish that. Update: Ah the answer resides on your comment, I have to pass the typeof class which is my profile. // services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature
– Esen
Sep 23 '17 at 16:35
This worked fine with .net core 1.1, not anymore once I upgraded to .net core 2.0. I think, I need to explicitly specify the logic profile class assembly. Still researching how to accomplish that. Update: Ah the answer resides on your comment, I have to pass the typeof class which is my profile. // services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature
– Esen
Sep 23 '17 at 16:35
|
show 9 more comments
theutz' answer here is very good, I just want to add this:
If you let your mapping profile inherit from MapperConfigurationExpression
instead of Profile
, you can very simply add a test to verify your mapping setup, which is always handy:
[Fact]
public void MappingProfile_VerifyMappings()
{
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(mappingProfile);
var mapper = new Mapper(config);
(mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
I am getting one error : "AutoMapper Extension Dependency injection is incompatible with asp.net core 1.1 ". Please help!
– Rohit Arora
Aug 31 '17 at 4:38
It seems the definition of "verify" is up for debate. This blows up when certain properties are ommitted by design to prevent mapping.
– Jeremy Holovacs
Mar 21 '18 at 19:36
1
If you don’t want a property mapped, set it up with .Ignore(). That way, it forces you to actively think about handling each case - making sure you don’t miss out on stuff when changes are being made. Super practical, actually. So yes, the verify-test is a larger safety net than many people realise. It’s not foolproof, but it takes care of the first 90%.
– Arve Systad
Mar 23 '18 at 5:13
add a comment |
theutz' answer here is very good, I just want to add this:
If you let your mapping profile inherit from MapperConfigurationExpression
instead of Profile
, you can very simply add a test to verify your mapping setup, which is always handy:
[Fact]
public void MappingProfile_VerifyMappings()
{
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(mappingProfile);
var mapper = new Mapper(config);
(mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
I am getting one error : "AutoMapper Extension Dependency injection is incompatible with asp.net core 1.1 ". Please help!
– Rohit Arora
Aug 31 '17 at 4:38
It seems the definition of "verify" is up for debate. This blows up when certain properties are ommitted by design to prevent mapping.
– Jeremy Holovacs
Mar 21 '18 at 19:36
1
If you don’t want a property mapped, set it up with .Ignore(). That way, it forces you to actively think about handling each case - making sure you don’t miss out on stuff when changes are being made. Super practical, actually. So yes, the verify-test is a larger safety net than many people realise. It’s not foolproof, but it takes care of the first 90%.
– Arve Systad
Mar 23 '18 at 5:13
add a comment |
theutz' answer here is very good, I just want to add this:
If you let your mapping profile inherit from MapperConfigurationExpression
instead of Profile
, you can very simply add a test to verify your mapping setup, which is always handy:
[Fact]
public void MappingProfile_VerifyMappings()
{
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(mappingProfile);
var mapper = new Mapper(config);
(mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
theutz' answer here is very good, I just want to add this:
If you let your mapping profile inherit from MapperConfigurationExpression
instead of Profile
, you can very simply add a test to verify your mapping setup, which is always handy:
[Fact]
public void MappingProfile_VerifyMappings()
{
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(mappingProfile);
var mapper = new Mapper(config);
(mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
answered Mar 30 '17 at 12:39
Arve SystadArve Systad
4,65012655
4,65012655
I am getting one error : "AutoMapper Extension Dependency injection is incompatible with asp.net core 1.1 ". Please help!
– Rohit Arora
Aug 31 '17 at 4:38
It seems the definition of "verify" is up for debate. This blows up when certain properties are ommitted by design to prevent mapping.
– Jeremy Holovacs
Mar 21 '18 at 19:36
1
If you don’t want a property mapped, set it up with .Ignore(). That way, it forces you to actively think about handling each case - making sure you don’t miss out on stuff when changes are being made. Super practical, actually. So yes, the verify-test is a larger safety net than many people realise. It’s not foolproof, but it takes care of the first 90%.
– Arve Systad
Mar 23 '18 at 5:13
add a comment |
I am getting one error : "AutoMapper Extension Dependency injection is incompatible with asp.net core 1.1 ". Please help!
– Rohit Arora
Aug 31 '17 at 4:38
It seems the definition of "verify" is up for debate. This blows up when certain properties are ommitted by design to prevent mapping.
– Jeremy Holovacs
Mar 21 '18 at 19:36
1
If you don’t want a property mapped, set it up with .Ignore(). That way, it forces you to actively think about handling each case - making sure you don’t miss out on stuff when changes are being made. Super practical, actually. So yes, the verify-test is a larger safety net than many people realise. It’s not foolproof, but it takes care of the first 90%.
– Arve Systad
Mar 23 '18 at 5:13
I am getting one error : "AutoMapper Extension Dependency injection is incompatible with asp.net core 1.1 ". Please help!
– Rohit Arora
Aug 31 '17 at 4:38
I am getting one error : "AutoMapper Extension Dependency injection is incompatible with asp.net core 1.1 ". Please help!
– Rohit Arora
Aug 31 '17 at 4:38
It seems the definition of "verify" is up for debate. This blows up when certain properties are ommitted by design to prevent mapping.
– Jeremy Holovacs
Mar 21 '18 at 19:36
It seems the definition of "verify" is up for debate. This blows up when certain properties are ommitted by design to prevent mapping.
– Jeremy Holovacs
Mar 21 '18 at 19:36
1
1
If you don’t want a property mapped, set it up with .Ignore(). That way, it forces you to actively think about handling each case - making sure you don’t miss out on stuff when changes are being made. Super practical, actually. So yes, the verify-test is a larger safety net than many people realise. It’s not foolproof, but it takes care of the first 90%.
– Arve Systad
Mar 23 '18 at 5:13
If you don’t want a property mapped, set it up with .Ignore(). That way, it forces you to actively think about handling each case - making sure you don’t miss out on stuff when changes are being made. Super practical, actually. So yes, the verify-test is a larger safety net than many people realise. It’s not foolproof, but it takes care of the first 90%.
– Arve Systad
Mar 23 '18 at 5:13
add a comment |
I want to extend @theutz's answers - namely this line :
// services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature.
There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)
This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:
services.AddAutoMapper();
unless you explicitly specify which assemblies to search AutoMapper profiles for.
It can be done like this in your Startup.ConfigureServices:
services.AddAutoMapper(<assembies> or <type_in_assemblies>);
where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:
services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));
I suppose (and I put emphasis on this word) that due to following implementaion of parameterless overaload (source code from GitHub) :
public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}
we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more deatils in this StackOverflow question).
add a comment |
I want to extend @theutz's answers - namely this line :
// services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature.
There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)
This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:
services.AddAutoMapper();
unless you explicitly specify which assemblies to search AutoMapper profiles for.
It can be done like this in your Startup.ConfigureServices:
services.AddAutoMapper(<assembies> or <type_in_assemblies>);
where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:
services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));
I suppose (and I put emphasis on this word) that due to following implementaion of parameterless overaload (source code from GitHub) :
public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}
we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more deatils in this StackOverflow question).
add a comment |
I want to extend @theutz's answers - namely this line :
// services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature.
There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)
This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:
services.AddAutoMapper();
unless you explicitly specify which assemblies to search AutoMapper profiles for.
It can be done like this in your Startup.ConfigureServices:
services.AddAutoMapper(<assembies> or <type_in_assemblies>);
where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:
services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));
I suppose (and I put emphasis on this word) that due to following implementaion of parameterless overaload (source code from GitHub) :
public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}
we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more deatils in this StackOverflow question).
I want to extend @theutz's answers - namely this line :
// services.AddAutoMapper(typeof(Startup)); // <-- newer automapper version uses this signature.
There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)
This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:
services.AddAutoMapper();
unless you explicitly specify which assemblies to search AutoMapper profiles for.
It can be done like this in your Startup.ConfigureServices:
services.AddAutoMapper(<assembies> or <type_in_assemblies>);
where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:
services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));
I suppose (and I put emphasis on this word) that due to following implementaion of parameterless overaload (source code from GitHub) :
public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}
we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more deatils in this StackOverflow question).
answered May 4 '18 at 15:30
GrayCatGrayCat
389515
389515
add a comment |
add a comment |
Step To Use AutoMapper with ASP.NET Core.
Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.
Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".
Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.
In this class, we are going to Maintain all Mappings.
Step 4. Initializing Mapper in Startup "ConfigureServices"
In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
Code Snippet to show ConfigureServices Method where we need to Initialize and Register 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);
}}
Step 5. Get Output.
To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
add a comment |
Step To Use AutoMapper with ASP.NET Core.
Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.
Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".
Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.
In this class, we are going to Maintain all Mappings.
Step 4. Initializing Mapper in Startup "ConfigureServices"
In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
Code Snippet to show ConfigureServices Method where we need to Initialize and Register 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);
}}
Step 5. Get Output.
To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
add a comment |
Step To Use AutoMapper with ASP.NET Core.
Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.
Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".
Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.
In this class, we are going to Maintain all Mappings.
Step 4. Initializing Mapper in Startup "ConfigureServices"
In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
Code Snippet to show ConfigureServices Method where we need to Initialize and Register 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);
}}
Step 5. Get Output.
To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
Step To Use AutoMapper with ASP.NET Core.
Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.
Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".
Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.
In this class, we are going to Maintain all Mappings.
Step 4. Initializing Mapper in Startup "ConfigureServices"
In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.
Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
services.AddAutoMapper();
Code Snippet to show ConfigureServices Method where we need to Initialize and Register 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);
}}
Step 5. Get Output.
To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.
AutoMapper.Mapper.Map<Destination>(source);
CodeSnippet
[HttpPost]
public void Post([FromBody] SchemeMasterViewModel schemeMaster)
{
if (ModelState.IsValid)
{
var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
}
}
edited Nov 24 '18 at 7:06
answered Nov 24 '18 at 6:18
SaineshwarSaineshwar
1,66232532
1,66232532
add a comment |
add a comment |
I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.
First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.
public class UserProfile : Profile, IProfile
{
public UserProfile()
{
CreateMap<User, UserModel>();
CreateMap<UserModel, User>();
}
}
Now create a separate class e.g Mappings
public class Mappings
{
public static void RegisterMappings()
{
var all =
Assembly
.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.SelectMany(x => x.DefinedTypes)
.Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
var t = ti.AsType();
if (t.Equals(typeof(IProfile)))
{
Mapper.Initialize(cfg =>
{
cfg.AddProfiles(t); // Initialise each Profile classe
});
}
}
}
}
Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application
loading.
Mappings.RegisterMappings();
You can just create a subclass from profile class, and when program is running services.AddAutoMapper(); line of codes The automapper automatically knows them.
– isaeid
Oct 1 '17 at 13:49
I don't think this is necessary if you use AutoMapper.Extensions.Microsoft.DependancyInjection which is available in nuget.
– Greg Gum
Aug 18 '18 at 10:43
add a comment |
I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.
First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.
public class UserProfile : Profile, IProfile
{
public UserProfile()
{
CreateMap<User, UserModel>();
CreateMap<UserModel, User>();
}
}
Now create a separate class e.g Mappings
public class Mappings
{
public static void RegisterMappings()
{
var all =
Assembly
.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.SelectMany(x => x.DefinedTypes)
.Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
var t = ti.AsType();
if (t.Equals(typeof(IProfile)))
{
Mapper.Initialize(cfg =>
{
cfg.AddProfiles(t); // Initialise each Profile classe
});
}
}
}
}
Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application
loading.
Mappings.RegisterMappings();
You can just create a subclass from profile class, and when program is running services.AddAutoMapper(); line of codes The automapper automatically knows them.
– isaeid
Oct 1 '17 at 13:49
I don't think this is necessary if you use AutoMapper.Extensions.Microsoft.DependancyInjection which is available in nuget.
– Greg Gum
Aug 18 '18 at 10:43
add a comment |
I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.
First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.
public class UserProfile : Profile, IProfile
{
public UserProfile()
{
CreateMap<User, UserModel>();
CreateMap<UserModel, User>();
}
}
Now create a separate class e.g Mappings
public class Mappings
{
public static void RegisterMappings()
{
var all =
Assembly
.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.SelectMany(x => x.DefinedTypes)
.Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
var t = ti.AsType();
if (t.Equals(typeof(IProfile)))
{
Mapper.Initialize(cfg =>
{
cfg.AddProfiles(t); // Initialise each Profile classe
});
}
}
}
}
Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application
loading.
Mappings.RegisterMappings();
I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.
First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.
public class UserProfile : Profile, IProfile
{
public UserProfile()
{
CreateMap<User, UserModel>();
CreateMap<UserModel, User>();
}
}
Now create a separate class e.g Mappings
public class Mappings
{
public static void RegisterMappings()
{
var all =
Assembly
.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.SelectMany(x => x.DefinedTypes)
.Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
var t = ti.AsType();
if (t.Equals(typeof(IProfile)))
{
Mapper.Initialize(cfg =>
{
cfg.AddProfiles(t); // Initialise each Profile classe
});
}
}
}
}
Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application
loading.
Mappings.RegisterMappings();
edited Oct 21 '18 at 13:02
Roy Scheffers
2,228101926
2,228101926
answered Jul 25 '17 at 1:19
AamirAamir
31457
31457
You can just create a subclass from profile class, and when program is running services.AddAutoMapper(); line of codes The automapper automatically knows them.
– isaeid
Oct 1 '17 at 13:49
I don't think this is necessary if you use AutoMapper.Extensions.Microsoft.DependancyInjection which is available in nuget.
– Greg Gum
Aug 18 '18 at 10:43
add a comment |
You can just create a subclass from profile class, and when program is running services.AddAutoMapper(); line of codes The automapper automatically knows them.
– isaeid
Oct 1 '17 at 13:49
I don't think this is necessary if you use AutoMapper.Extensions.Microsoft.DependancyInjection which is available in nuget.
– Greg Gum
Aug 18 '18 at 10:43
You can just create a subclass from profile class, and when program is running services.AddAutoMapper(); line of codes The automapper automatically knows them.
– isaeid
Oct 1 '17 at 13:49
You can just create a subclass from profile class, and when program is running services.AddAutoMapper(); line of codes The automapper automatically knows them.
– isaeid
Oct 1 '17 at 13:49
I don't think this is necessary if you use AutoMapper.Extensions.Microsoft.DependancyInjection which is available in nuget.
– Greg Gum
Aug 18 '18 at 10:43
I don't think this is necessary if you use AutoMapper.Extensions.Microsoft.DependancyInjection which is available in nuget.
– Greg Gum
Aug 18 '18 at 10:43
add a comment |
services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)
After configuring as below
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientCustomer, Models.Customer>();
});
initialize the mapper
IMapper mapper = config.CreateMapper();
and add the mapper object to services as a singleton
services.AddSingleton(mapper);
this way I am able to add a DI to controller
private IMapper autoMapper = null;
public VerifyController(IMapper mapper)
{
autoMapper = mapper;
}
and I have used as below in my action methods
ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);
add a comment |
services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)
After configuring as below
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientCustomer, Models.Customer>();
});
initialize the mapper
IMapper mapper = config.CreateMapper();
and add the mapper object to services as a singleton
services.AddSingleton(mapper);
this way I am able to add a DI to controller
private IMapper autoMapper = null;
public VerifyController(IMapper mapper)
{
autoMapper = mapper;
}
and I have used as below in my action methods
ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);
add a comment |
services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)
After configuring as below
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientCustomer, Models.Customer>();
});
initialize the mapper
IMapper mapper = config.CreateMapper();
and add the mapper object to services as a singleton
services.AddSingleton(mapper);
this way I am able to add a DI to controller
private IMapper autoMapper = null;
public VerifyController(IMapper mapper)
{
autoMapper = mapper;
}
and I have used as below in my action methods
ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);
services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)
After configuring as below
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientCustomer, Models.Customer>();
});
initialize the mapper
IMapper mapper = config.CreateMapper();
and add the mapper object to services as a singleton
services.AddSingleton(mapper);
this way I am able to add a DI to controller
private IMapper autoMapper = null;
public VerifyController(IMapper mapper)
{
autoMapper = mapper;
}
and I have used as below in my action methods
ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);
answered Mar 24 '18 at 15:27
Venkat pvVenkat pv
253
253
add a comment |
add a comment |
For ASP.NET Core, the following is direct from Automapper and is 1 line in your startup class:
https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/README.md
Simply add some profile classes. Then add below to your startup.cs class.
services.AddAutoMapper(OneOfYourProfileClassNamesHereSoItCanFindYourProfileAssembly)
Then simply Inject IMapper in your controllers or wherever you need it:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper)
=> _mapper = mapper;
// use _mapper.Map to map
}
And if you want to use ProjectTo its now simply:
var customers = await dbContext.Customers.ProjectTo<CustomerDto>(_mapper.ConfigurationProvider).ToListAsync()
add a comment |
For ASP.NET Core, the following is direct from Automapper and is 1 line in your startup class:
https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/README.md
Simply add some profile classes. Then add below to your startup.cs class.
services.AddAutoMapper(OneOfYourProfileClassNamesHereSoItCanFindYourProfileAssembly)
Then simply Inject IMapper in your controllers or wherever you need it:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper)
=> _mapper = mapper;
// use _mapper.Map to map
}
And if you want to use ProjectTo its now simply:
var customers = await dbContext.Customers.ProjectTo<CustomerDto>(_mapper.ConfigurationProvider).ToListAsync()
add a comment |
For ASP.NET Core, the following is direct from Automapper and is 1 line in your startup class:
https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/README.md
Simply add some profile classes. Then add below to your startup.cs class.
services.AddAutoMapper(OneOfYourProfileClassNamesHereSoItCanFindYourProfileAssembly)
Then simply Inject IMapper in your controllers or wherever you need it:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper)
=> _mapper = mapper;
// use _mapper.Map to map
}
And if you want to use ProjectTo its now simply:
var customers = await dbContext.Customers.ProjectTo<CustomerDto>(_mapper.ConfigurationProvider).ToListAsync()
For ASP.NET Core, the following is direct from Automapper and is 1 line in your startup class:
https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/README.md
Simply add some profile classes. Then add below to your startup.cs class.
services.AddAutoMapper(OneOfYourProfileClassNamesHereSoItCanFindYourProfileAssembly)
Then simply Inject IMapper in your controllers or wherever you need it:
public class EmployeesController {
private readonly IMapper _mapper;
public EmployeesController(IMapper mapper)
=> _mapper = mapper;
// use _mapper.Map to map
}
And if you want to use ProjectTo its now simply:
var customers = await dbContext.Customers.ProjectTo<CustomerDto>(_mapper.ConfigurationProvider).ToListAsync()
edited Feb 19 at 9:03
answered Feb 19 at 6:26
user1191559user1191559
532517
532517
add a comment |
add a comment |
about theutz answer ,
there is no need to specify the IMapper mapper parrameter at the controllers constructor.
you can use the Mapper as it is a static member at any place of the code.
public class UserController : Controller {
public someMethod()
{
Mapper.Map<User, UserDto>(user);
}
}
8
But statics are a bit anti-testable, no?
– Scott Fraley
May 17 '17 at 17:40
2
Yep. This will work in many cases, but if you have no configured mapping when invoking this method in a test, It'll throw an exception (and thus failing the test for the wrong reason). With an injectedIMapper
you can mock that and, for example, just make it return null if it's irrelevant for the given test.
– Arve Systad
May 29 '17 at 20:48
add a comment |
about theutz answer ,
there is no need to specify the IMapper mapper parrameter at the controllers constructor.
you can use the Mapper as it is a static member at any place of the code.
public class UserController : Controller {
public someMethod()
{
Mapper.Map<User, UserDto>(user);
}
}
8
But statics are a bit anti-testable, no?
– Scott Fraley
May 17 '17 at 17:40
2
Yep. This will work in many cases, but if you have no configured mapping when invoking this method in a test, It'll throw an exception (and thus failing the test for the wrong reason). With an injectedIMapper
you can mock that and, for example, just make it return null if it's irrelevant for the given test.
– Arve Systad
May 29 '17 at 20:48
add a comment |
about theutz answer ,
there is no need to specify the IMapper mapper parrameter at the controllers constructor.
you can use the Mapper as it is a static member at any place of the code.
public class UserController : Controller {
public someMethod()
{
Mapper.Map<User, UserDto>(user);
}
}
about theutz answer ,
there is no need to specify the IMapper mapper parrameter at the controllers constructor.
you can use the Mapper as it is a static member at any place of the code.
public class UserController : Controller {
public someMethod()
{
Mapper.Map<User, UserDto>(user);
}
}
answered May 10 '17 at 5:38
yaronmilyaronmil
3814
3814
8
But statics are a bit anti-testable, no?
– Scott Fraley
May 17 '17 at 17:40
2
Yep. This will work in many cases, but if you have no configured mapping when invoking this method in a test, It'll throw an exception (and thus failing the test for the wrong reason). With an injectedIMapper
you can mock that and, for example, just make it return null if it's irrelevant for the given test.
– Arve Systad
May 29 '17 at 20:48
add a comment |
8
But statics are a bit anti-testable, no?
– Scott Fraley
May 17 '17 at 17:40
2
Yep. This will work in many cases, but if you have no configured mapping when invoking this method in a test, It'll throw an exception (and thus failing the test for the wrong reason). With an injectedIMapper
you can mock that and, for example, just make it return null if it's irrelevant for the given test.
– Arve Systad
May 29 '17 at 20:48
8
8
But statics are a bit anti-testable, no?
– Scott Fraley
May 17 '17 at 17:40
But statics are a bit anti-testable, no?
– Scott Fraley
May 17 '17 at 17:40
2
2
Yep. This will work in many cases, but if you have no configured mapping when invoking this method in a test, It'll throw an exception (and thus failing the test for the wrong reason). With an injected
IMapper
you can mock that and, for example, just make it return null if it's irrelevant for the given test.– Arve Systad
May 29 '17 at 20:48
Yep. This will work in many cases, but if you have no configured mapping when invoking this method in a test, It'll throw an exception (and thus failing the test for the wrong reason). With an injected
IMapper
you can mock that and, for example, just make it return null if it's irrelevant for the given test.– Arve Systad
May 29 '17 at 20:48
add a comment |
To add onto what Arve Systad mentioned for testing. If for whatever reason you're like me and want to maintain the inheritance structure provided in theutz solution, you can set up the MapperConfiguration like so:
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(mappingProfile);
});
var mapper = new Mapper(config);
I did this in NUnit.
add a comment |
To add onto what Arve Systad mentioned for testing. If for whatever reason you're like me and want to maintain the inheritance structure provided in theutz solution, you can set up the MapperConfiguration like so:
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(mappingProfile);
});
var mapper = new Mapper(config);
I did this in NUnit.
add a comment |
To add onto what Arve Systad mentioned for testing. If for whatever reason you're like me and want to maintain the inheritance structure provided in theutz solution, you can set up the MapperConfiguration like so:
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(mappingProfile);
});
var mapper = new Mapper(config);
I did this in NUnit.
To add onto what Arve Systad mentioned for testing. If for whatever reason you're like me and want to maintain the inheritance structure provided in theutz solution, you can set up the MapperConfiguration like so:
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(mappingProfile);
});
var mapper = new Mapper(config);
I did this in NUnit.
answered Mar 9 '18 at 20:18
LandSharksLandSharks
74210
74210
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40275195%2fhow-to-setup-automapper-in-asp-net-core%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
See dotnetcoretutorials.com/2017/09/23/…
– Michael Freidgeim
Dec 8 '17 at 6:15
For newer versions of core (>v1) check out @Saineshwar's answer stackoverflow.com/a/53455699/833878
– Robbie
Feb 16 at 21:01