I am new of ASP.NET BoilerPlate (ABP) and I am trying to understand how to create custom mappings using AutoMapper and, maybe, the ABP automapper attributes: AutoMap, AutoMapFrom, AutoMapTo.
With ABP I can map two classes in this way:
[AutoMapTo(typeof(DestClass)]
public class SourceClass {
public string A { get; set; }
public string B { get; set; }
}
public class DestClass {
public string A { get; set; }
public string B { get; set; }
}
But if I have two classes like the following where I want the property AB to be automapped as a join of A and B:
[AutoMapTo(typeof(DestClass)]
public class SourceClass {
public string A { get; set; }
public string B { get; set; }
}
public class DestClass {
public string AB { get; set; }
}
Are there some attributes with ABP? Or do I need to use the "classical" AutoMapper code:
Mapper.CreateMap<SourceClass, DestClass>()
.ForMember(dest => dest.AB,
opts => opts.MapFrom(src => (src.A + ", " + src.B)));
And where do I have to place such init code?
I found a solution I share here.
In "MyProject.Application" project I defined my automapper customs (I used profiles):
public class MyProjectAutoMapperProfile : AutoMapper.Profile {
protected override void Configure() {
CreateMap<SourceClass, DestClass>()
.ForMember(dest => dest.AB,
opts => opts.MapFrom(src => (src.A + ", " + src.B)));
// other customs here...
}
Then I registered it for injection in the Initialize method of the class MyProjectApplicationModule:
[DependsOn(typeof(MyProjectCoreModule), typeof(AbpAutoMapperModule))]
public class MyProjectApplicationModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
// --- MY CODE for registering custom automapping
var mapperConfiguration = new MapperConfiguration(cfg => {
cfg.AddProfile(new MyProjectMapperProfile()); // <= here my custom mapping
});
var mapper = mapperConfiguration.CreateMapper();
IocManager.IocContainer.Register(
Castle.MicroKernel.Registration.Component.For<IMapper>().Instance(mapper)
);
// --- MY CODE
}
}
Note that I directly used the Castle IOC register methods because I did not find any useful registering method for objects in ABP. Do you know one?
Finally I used my custom mapping as injection in my Application Service and used it directly:
public class MyAppService : MyNewHouseAppServiceBase, IMyAppService {
// ...
public MyAppService(IRepository<SourceClass, long> myRepository, AutoMapper.IMapper mapper) {
_myRepo = myRepository;
_mapper = mypper;
}
public async Task<DestClass> GetSource(long id) {
var source = await _myRepo.Find(id);
// USE THE INJECTED MAPPER
return _mapper.Map<DestClass>(source);
}
public async Task<ListResultOutput<DestClass>> GetSources() {
var sources = await _myRepo.GetAllListAsync();
return new ListResultOutput<DestClass>(
// USE THE INJECTED MAPPER
_mapper.Map<List<DestClass>>(sources)
);
}
}
No need to list all the customer mapping on the Module. Just tell the module to find all the classes which extend AutoMapper.Profile:
Assembly thisAssembly = typeof(AbpProjectNameApplicationModule).GetAssembly();
IocManager.RegisterAssemblyByConvention(thisAssembly);
cfg.AddProfiles(thisAssembly);
Related
I am trying to use AutoMapper to map a DTO to an Entity class but I keep getting an error.
Here is the DTO Class:
public class Product
{
public string ID { get; set; }
public string SKU { get; set; }
public string Name { get; set; }
public PriceTiers PriceTiers { get; set; }
}
and here is the Entity:
public partial class Product
{
public Product()
{
PriceTiers = new List<PriceTiers>();
}
[Key]
public string ID { get; set; }
public string SKU { get; set; }
public string Name { get; set; }
public virtual ICollection<PriceTiers> PriceTiers { get; set; }
}
Why do I keep getting the following error?
{"Missing type map configuration or unsupported
mapping.\r\n\r\nMapping types:\r\nPriceTiers ->
ICollection1\r\nWeb.Areas.DEAR.DTOs.PriceTiers -> System.Collections.Generic.ICollection1[[Web.Areas.DEAR.Data.PriceTiers,
Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]\r\n\r\n
Destination Member:\r\nPriceTiers\r\n"}
This is what I have in the Profile class:
AllowNullCollections = true;
CreateMap<DTOs.Product, Data.Product>();
CreateMap<DTOs.PriceTiers, Data.PriceTiers>();
and this is what I use to map the classes:
var products = _mapper.Map<IEnumerable<Product>>(result.Products);
This is what is in the Program.cs:
builder.Services.AddAutoMapper(typeof(AutoMapperProfiles).Assembly);
The exception message is quite clear, the AutoMapper doesn't know how to map the data from DTOs.PriceTiers to ICollection<Data.PriceTiers>.
Solution 1: Map from DTOs.PriceTiers to ICollection<Data.PriceTiers>
I believe that Custom Type Converters is what you need.
Create Custom Type Converters.
public class ICollectionDataPriceTiersTypeConverter : ITypeConverter<DTOs.PriceTiers, ICollection<Data.PriceTiers>>
{
public ICollection<Data.PriceTiers> Convert(DTOs.PriceTiers src, ICollection<Data.PriceTiers> dest, ResolutionContext context)
{
if (src == null)
return default;
var singleDest = context.Mapper.Map<Data.PriceTiers>(src);
return new List<Data.PriceTiers>
{
singleDest
};
}
}
Add to mapping profile.
CreateMap<DTOs.PriceTiers, ICollection<Data.PriceTiers>>()
.ConvertUsing<ICollectionDataPriceTiersTypeConverter>();
Demo # .NET Fiddle
Solution 2: Map from ICollection<DTOs.PriceTiers> to ICollection<Data.PriceTiers>
If the PriceTiers in DTOs.Product supports multiple items and mapping with many to many (to ICollection<Data.ProductTiers>), then consider modifying the property as the ICollection<DTOs.PriceTiers> type.
namespace DTOs
{
public class Product
{
...
public ICollection<PriceTiers> PriceTiers { get; set; }
}
}
Did you added "CreateMapper()" method after your configurations?
Try something like that.
public class MappingProfile : Profile
{
public MappingProfile {
AllowNullCollections = true;
CreateMap<DTOs.Product, Data.Product>();
CreateMap<DTOs.PriceTiers, Data.PriceTiers>();
}
}
After that, on your container service, inject this dependency:
var mappingConfig = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
builder.Services.AddSingleton(mapper);
After some more research I found out that my mapping profile was not in the right order. These are the changes I made.
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
AllowNullCollections = true;
CreateMap<DTOs.PriceTiers, Data.PriceTiers>();
CreateMap<DTOs.Product, Data.Product>()
.ForMember(dto => dto.PriceTiers, opt => opt.MapFrom(x => x.PriceTiers));
}
}
Now it maps perfectly
Got a mapper configuration which includes:
this.CreateMap<MyProp1, MyDesintationProp>();
this.CreateMap<MyProp2, MyDesintationProp>();
Then, inside the mapper for a more complex object, both these are used inside an inline ResolveUsing to merge into a list of MyDestinationProp:
.ForMember(dest => dest.MyDesintationPropList, opt => opt.ResolveUsing(tc =>
{
var results = new List<MyDesintationProp>();
if (tc.MyProp1 != null)
{
results.Add(Mapper.Map<MyDestinationProp>(tc.MyProp1));
}
if (tc.MyProp2 != null)
{
results.Add(Mapper.Map<MyDestinationProp>(tc.MyProp2));
}
return results;
}))
This works fine in production, but causes tests on this mapping to blow up, complaining
Property:
MyDestinationProp
---- System.InvalidOperationException : Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.
Which I guess makes sense because the mapper inside the mapper hasn't been initialised. But what's the best way to go about fixing this?
This is a very trivial example, that really doesn't need to use the context, cause it would also work with simple mappings.
public class Source
{
public string Name { get; set; }
public SourceChild Child { get; set; }
public override string ToString() => $"{typeof(Source)} -> {Name}";
}
public class Destination
{
public string Name { get; set; }
public DestinationChild Child { get; set; }
public override string ToString() => $"{typeof(Destination)} -> {Name}";
}
public class SourceChild
{
public string Name { get; set; }
public override string ToString() => $"{typeof(SourceChild)} -> {Name}";
}
public class DestinationChild
{
public string Name { get; set; }
public override string ToString() => $"{typeof(DestinationChild)} -> {Name}";
}
public class MappingContextProfile : Profile
{
public MappingContextProfile()
{
CreateMap<Source, Destination>()
.ForMember(source => source.Child, conf => conf.MapFrom((source, destination, destinationChild, context) =>
{
// Not really needed in this case, cause it does just some simple mapping.
// But if you would need to add some informations from outside
// (e.g. some interface mapping, etc)
// this would be the place without losing the magic of AutoMapper.
return context.Mapper.Map<DestinationChild>(source.Child);
}));
CreateMap<SourceChild, DestinationChild>();
}
}
public class MappingSimpleProfile : Profile
{
public MappingSimpleProfile()
{
CreateMap<Source, Destination>();
CreateMap<SourceChild, DestinationChild>();
}
}
public static class Program
{
public static async Task<int> Main(string[] args)
{
var config = new MapperConfiguration(cfg => cfg.AddProfile<MappingContextProfile>());
var mapper = config.CreateMapper();
var sources = Enumerable.Range(1, 10)
.Select(i => new Source { Name = $"{i}", Child = new SourceChild { Name = $"{i * 100}" } })
.ToList();
var destinations = mapper.Map<List<Destination>>(sources);
foreach (var item in destinations)
{
Console.WriteLine($"{item} -> {item.Child}");
}
return 0;
}
}
I use AutoMapper in my .NET CORE 2.2 project.
I get this exception:
Missing type map configuration or unsupported mapping.
Mapping types:
SaveFridgeTypeModel -> FridgeType
College.Refrigirator.Application.SaveFridgeTypeModel ->
College.Refrigirator.Domain.FridgeType
On This row:
var fridgeType = _mapper.Map<SaveFridgeTypeModel, FridgeType>(model);
Here is defenition of FridgeType class:
public class FridgeType : IEntity , IType
{
public FridgeType()
{
Fridges = new HashSet<Fridge>();
}
public int ID { get; set; }
//Description input should be restricted
public string Description { get; set; }
public string Text { get; set; }
public ICollection<Fridge> Fridges { get; private set; }
}
Here is defenition of SaveFridgeTypeModel class:
public class SaveFridgeTypeModel
{
public string Description { get; set; }
public string Text { get; set; }
}
I add this row:
services.AddAutoMapper(typeof(Startup));
To ConfigureServices function in Startup class.
UPDATE
I forgot to add mappin configuration to the post.
Here is mapping configs class:
public class ViewModelToEntityProfile : Profile
{
public ViewModelToEntityProfile()
{
CreateMap<SaveFridgeTypeModel, FridgeType>();
}
}
Any idea why I get the exception above?
You need to use the type from the assembly where your maps are when registering automapper with DI.
AddAutomapper(typeof(ViewModelToEntityProfile));
If you had multiple assemblies with maps - you could use another overload:
AddAutomapper(typeof(ViewModelToEntityProfile), typeof(SomeOtherTypeInOtherAssembly));
After creating mapping config class you need to 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 ViewModelToEntityProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddMvc();
}
Im trying to map a Class which inherits from a base class to a dto.
public class LaunchConfiguration : Document
{
public string Brand { get; set; }
public string SettingName{ get; set; }
}
public class LaunchConfigurationDto
{
public string Brand { get; set; }
public string SettingName{ get; set; }
}
The point of the dto is to hide the fields of the base document when it gets returned to the user. This is my Map configuration
public class DtoProfile : Profile
{
public DtoProfile()
{
CreateMap<LaunchConfiguration,LaunchConfigurationDto>();
}
};
The problem im having is that auto mapper complains about the base class properties which are not mapped . "Unmapped members were found." The properties are the ones on the base class. I have tried specifying this to be ignored in the profile to no avail . Can anyone specify the correct way to do this ?
My ConfigureServices Method incase anyone is wondering :
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = Configuration["ApiInformation:Name"], Version = Configuration["ApiInformation:Version"] });
c.DescribeAllEnumsAsStrings();
});
services.AddAutoMapper(mc =>
{
mc.AddProfile(new DtoProfile());
});
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});
}
My Base Class :
public class Document : IDocument, IDocument<Guid>
{
public Document()
{
this.Id = Guid.NewGuid();
this.AddedAtUtc = DateTime.UtcNow;
}
/// <summary>The Id of the document</summary>
[BsonId]
public Guid Id { get; set; }
/// <summary>The datetime in UTC at which the document was added.</summary>
public DateTime AddedAtUtc { get; set; }
/// <summary>The version of the schema of the document</summary>
public int Version { get; set; }
}
My implementation where _mapper is my Injected mapper and _repo My Injected Repo. Exception Occurs on Map Method call
Task ILaunchConfigurationService<LaunchConfigurationDto >.InsertLaunchConfiguration(LaunchConfigurationDto model)
{
var mapped = _mapper.Map<LaunchConfiguration >(model);
return _repo.AddOneAsync(mapped);
}
Your problem should be solved by simply adding ReverseMap() to CreateMap call:
public class DtoProfile : Profile
{
public DtoProfile()
{
CreateMap<LaunchConfiguration, LaunchConfigurationDto>().ReverseMap();
}
};
Automapper creates one way map by default. ReverseMap is just a sugar for creating reverse map in case there are no peculiar mappings in one way. You could also do it like this:
public class DtoProfile : Profile
{
public DtoProfile()
{
CreateMap<LaunchConfiguration, LaunchConfigurationDto>();
CreateMap<LaunchConfigurationDto, LaunchConfiguration>();
}
};
You can read more about this in documentation
However I cannot guarantee you that you will not experience exceptions from database with your current implementation on commiting changes.
I've just started with AutoMapper in C#. I've succesfully created a mapping like this:
Mapper.CreateMap<InputTypeA, OutputTypeA>()
I've also found a way to add some logic to specific properties, like formatting a date (in InputTypeA) to a string in a specific format (in OutputTypeA).
.ForMember(
dest => dest.MyDateProperty,
opt => opt.ResolveUsing(
src => String.Format("{0:yyyy-MM-dd}", src.MyDateProperty)));
Now I need to do the same for a number of float properties, but I'm wondering if there is a short/easy way to do this, except copying a piece of code like the one above for every property that needs to follow this rule.
I've found that I can create a new map like this for mapping floats to strings:
Mapper.CreateMap<float,string>()
.ConvertUsing(src =>
String.Format(CultureInfo.InvariantCulture.NumberFormat, "{0:0.00}", src));
This works, but is too generic, because I also have a mapping for another type (let's call it InputTypeB), that also contains float properties, which need to be treated differently.
Mapper.CreateMap<InputTypeB, OutputTypeB>()
How can I make the float-to-string mapping part of the first mapping only?
You could create two separate mappers based on two separate configurations, only one of which includes the float-to-string mapping:
public class InputTypeA { public float Foo { get; set; } }
public class OutputTypeA { public string Foo { get; set; } }
public class InputTypeB { public float Bar { get; set; } }
public class OutputTypeB { public string Bar { get; set; } }
public class Program
{
public static void Main(string[] args)
{
Func<float, string> mapFunc =
src => String.Format(CultureInfo.InvariantCulture.NumberFormat, "{0:0.00}", src);
var floatToStringConfig = new MapperConfiguration(cfg =>
{
cfg.CreateMap<InputTypeA, OutputTypeA>();
cfg.CreateMap<float, string>().ConvertUsing(mapFunc);
});
var regularConfig = new MapperConfiguration(cfg =>
{
cfg.CreateMap<InputTypeB, OutputTypeB>();
});
IMapper floatToStringMapper = floatToStringConfig.CreateMapper();
IMapper regularMapper = regularConfig.CreateMapper();
var aIn = new InputTypeA() { Foo = 1f };
var aOut = floatToStringMapper.Map<OutputTypeA>(aIn);
Console.WriteLine(aOut.Foo); // prints "1.00"
var bIn = new InputTypeB() { Bar = 1f };
var bOut = regularMapper.Map<OutputTypeB>(bIn);
Console.WriteLine(bOut.Bar); // prints "1"
}
}
You can create custom value resolvers for each case you need to handle. Then apply these to the appropriate members in your mappings.
As an example, I need to map from TypeA to TypeB, I only want DateB to use the custom conversion:
public class TypeA {
public DateTime DateA { get; set; }
public DateTime DateB { get; set; }
}
public class TypeB {
public string DateA { get; set; }
public string DateB { get; set; }
}
I create a custom resolver:
class DateStringResolver : ValueResolver<DateTime, string> {
protected override string ResolveCore(DateTime source) {
return String.Format("{0:yyyy-MM-dd}", source);
}
}
Then in my mapper config:
Mapper.CreateMap<TypeA, TypeB>()
//Only Date B will use our custom resolver
.ForMember(d => d.DateB, opt => opt.ResolveUsing<DateStringResolver>().FromMember(src => src.DateA));
The resolver can now be applied wherever it is needed.
Docs:https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers