We are mapping domain hierarchy to the Dto hierarchy. Some of the properties of the domain base class get flattened. We are using ReverseMap to simplify the mapping back to domain from dto.
We've mapped Contained.Id do ContainedId of Dto and ignored the path for the reverse map.
What we were expecting, that mapping back to domain object shouldn't create new instances for Contained-property. But that was not the case.
After some investigations we've found out, that it was due to not-inheriting the .ForPath(, opt => opt.Ignore()) for the ReverseMap.
We are using 9.0.0 version of Automapper.
Here is the code:
public class Contained {
public Guid Id { get; set; }
}
public class Base {
public Contained Contained { get; set;}
}
public class Derived: Base { }
public abstract class BaseDto {
public Guid? ContainedId { get; set; }
}
public class DerivedDto: BaseDto { }
[Test]
public void ForPathInheritanceWorks()
{
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Base, BaseDto>()
.IncludeAllDerived()
.ReverseMap()
.ForPath(d => d.Contained.Id, opt => opt.Ignore());
cfg.CreateMap<Derived, DerivedDto>()
.ReverseMap();
});
var mapper = configuration.CreateMapper();
var derived = mapper.Map<Derived>(new DerivedDto());
Assert.That(derived.Contained, Is.Null); // fails, because derived.Contained is not null.
}
To workaround an issue we had to add
.ForPath(d => d.Contained.Id, opt => opt.Ignore())
after ReverseMap of the derived class.
For me it looks like a bug in Automapper.
Related
I have an object model something like this:
public class Concert {
public Band Band { get; set; }
public ConcertVenue Venue { get; set; }
}
public class TicketOrder {
public Concert Concert { get; set; }
public string CustomerName { get; set; }
}
// DTOs for email and web views:
public class ConcertDto {
public string Artist { get; set; }
public string Venue { get; set; }
}
public class TicketOrderDto : ConcertDto {
public string CustomerName { get; set; }
}
I'm using AutoMapper to map domain objects to DTOs. The DTOs here have an inheritance relationship that doesn't exist in the domain model (because when I send an email about a ticket order, I want to include all the information about the concert)
I have a mapping defined like this:
config.CreateMap<Concert, ConcertDto>()
.ForMember(dto => dto.Artist, opt => opt.MapFrom(concert => concert.Band.Name))
.ForMember(dto => dto.Venue, opt => opt.MapFrom(concert => concert.GetVenueSummary());
config.CreateMap<TicketOrder, ConcertDto>()
.ForMember(dto => dto.Artist, opt => opt.MapFrom(concert => concert.Band.Name))
.ForMember(dto => dto.Venue, opt => opt.MapFrom(concert => concert.GetVenueSummary())
.ForMember(dto => dto.CustomerName, optn.MapFrom(order => order.Customer.FullName))
;
There's some duplication in those maps, and what I want to do is to reuse the Concert > ConcertViewData mapping when I map the TicketOrderDto:
cfg.CreateMap<TicketOrder, TicketOrderDto>()
// This is what I *want* but isn't valid AutoMapper syntax:
.IncludeMembers(dto => dto, order => order.Concert)
.ForMember(dto => dto.CustomerName, optn.MapFrom(order => order.Customer.FullName));
but this fails with:
System.ArgumentOutOfRangeException: Only member accesses are allowed.
dto => dto (Parameter 'memberExpressions')
at AutoMapper.ExpressionExtensions.EnsureMemberPath(LambdaExpression exp, String name)
Calling .IncludeBase<> doesn't work, because ConcertOrder doesn't derive from Concert.
Is there an easy way to import one map into another but specify that it should map from a child object of the source type? i.e. "hey, please map source.Child onto this, and then run the regular source > this mapping?"
I am going to make an assumption here, but I believe the mapping should be from TicketOrder to TicketOrderDto, and not ConcertDto (which contains no CustomerName property) as the given models don't match the given mapping configuration.
In that case, you should be able to use .AfterMap() on ticket mapper configuration to map from Concert to ConcertDto.
cfg.CreateMap<TicketOrder, TicketOrderDto>()
.ForMember(d => d.CustomerName, o => o.MapFrom(s => s.Order.Customer.Name))
.AfterMap((s, d, context) => context.Mapper.Map(s.Concert, d));
I'm working with .NET Core 2.0 and AutoMapper 6.2.2.
I'm using AssertConfigurationIsValid to make sure my mappings are correct and I have defined a number of AutoMapper.Profile which share some mapping rules:
Since I'm mapping between model entities and DTOs, I want field id
to be ignored in every entity <=> DTO mapping.
I also want AutoGeneratedAppid to be mapped to AppId in every
entity <=> DTO mapping.
For instance:
public class Role
{
public long Id { get; set; }
public string AutoGeneratedAppId { get; set; }
public string Name { get; set; }
}
public class RoleDTO
{
public string AppId { get; set; }
public string Name { get; set; }
}
public class RoleProfile : AutoMapper.Profile
{
public RoleProfile()
{
CreateMap<Role, RoleDTO>();
CreateMap<RoleDTO, Role>();
//.ForMember(entity => entity.Id, opt => opt.Ignore())
//.ForMember(entity => entity.AutoGeneratedAppId, opt => opt.MapFrom(dto => dto.AppId));
}
}
Since there both multiple mappings and multiple fields to be ignored/mapped in the same way in each mapping, I'm trying to found a way of avoiding having to define in every profile common rules this like:
.ForMember(entity => entity.Id, opt => opt.Ignore());
.ForMember(entity => entity.AutoGeneratedAppId, opt => opt.MapFrom(dto => dto.AppId));
I can't find a way to avoid a AutoMapperConfigurationException in AssertConfigurationIsValid when mapping dto => entity due to unmapped id and AutoGeneratedAppId properties.
My mapper configuration, with my failed trials, is the following:
protected override MapperConfiguration CreateConfiguration()
{
var config = new MapperConfiguration(cfg =>
{
cfg.DisableConstructorMapping();
cfg.AddProfiles(Assemblies);
// Global ignoring - alternative 1
cfg.ShouldMapProperty = prop =>
prop.Name != "Id";
// Global ignoring - alternative 2
cfg.AddGlobalIgnore("Id");
// Global ignoring - alternative 3
cfg.ForAllPropertyMaps(map =>
map.SourceMember.Name.EndsWith("Id"),
(map, configuration) =>
{
configuration.Ignore();
});
// Entity.AutoGeneratedAppId => DTO.AppId
cfg.RecognizePrefixes("AutoGenerated");
// DTO.AppId => Entity.AutoGeneratedAppId
cfg.RecognizeDestinationPrefixes("AutoGenerated");
});
return config;
}
My Startup configuration is the following:
var mapperProvider = new MapperProvider();
services.AddSingleton<IMapper>(mapperProvider.GetMapper());
services.AddAutoMapper(mapperProvider.Assemblies);
Thanks in advance.
I am in need to map the below scenario.
public class Customer
{
public string CustomerJson { get; set; }
}
public class CustomerTO
{
public object CustomerJson { get; set; }
}
From DAL I get CustomerJson value as below.
Customer.CustomerJson = {
"name": "Ram",
"city": "India"
}
I am in need to Deserialize this string. so I tried the below stuff while mapping.
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, CustomerTO>()
.ForMember(dest => dest.CustName, opt => opt.MapFrom(src => JsonConvert.DeserializeObject(src.CustName)));
});
But this gives me run time error.
Unhandled Exception: AutoMapper.AutoMapperMappingException: Error mapping types.
So I kept it simple.
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, CustomerTO>()
.ForMember(dest => dest.CustName, opt => opt.MapFrom(src => (src.CustName));
});
And I tried to deserialize it while consuming. But this give compile time error.
var custJson = JsonConvert.DeserializeObject(customerTO.CustomerJson );
Error 2 The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject(string)' has some invalid arguments
I know customerTO.CustomerJson is not string but how do should I do the required mapping?
Thanks.
Based on your previous question and given the information above you seem to be confusing what you're trying to do here.
So I'm going to amalgamate the data from both in an attempt to solve the issues.
Entity Classes:
public class Customer
{
public int CustomerId {get; set; }
public string CustomerName { get; set; }
public string CustomerJson { get; set; }
}
public class CustomerTO
{
public int CustId { get; set; }
public object CustData { get; set; }
public object CustomerJson { get; set; }
}
AppMapper Class:
public static class AppMapper
{
public static MapperConfiguration Mapping()
{
return new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, CustomerTO>()
.ForMember(dest => dest.CustId, opt => opt.MapFrom(src => src.CustomerId))
.ForMember(dest => dest.CustData, opt => opt.MapFrom(src => src.CustName))
.ForMember(dest => dest.CustomerJson, opt => opt.MapFrom(src => JsonConvert.DeserializeObject(src.CustomerJson));
});
}
}
Main:
public class Program
{
static void Main(string[] args)
{
var config = AppMapper.Mapping();
var mapper = config.CreateMapper();
// From Previous question get list of Customer objects
var customers = AddCustomers();
var mappedCustomers = mapper.Map<IEnumerable<CustomerTO>>(customers);
}
}
A couple of things to point out
I'm not sure what the purpose of CustData is in CustomerTO. It seems to be duplicating CustomerJson and if so remove it and the associated mapping.
Also, you never mention mapping from DTO back to entity, but for the JsonObject you just need to configure it to map the serialized string to the appropriate Property.
This is how I addressed my requirement.
Db Entity
public class Customer
{
public string CustomerData { get; set; }
// & other properties
}
My DTO
public class CustomerTO
{
public object CustomerData { get; set;}
// & other properties
}
I created a Utility like class with name AppMapper. This is how my AppMapper.cs looks like.
public class AppMapper
{
private IMapper _mapper;
public AppMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, CustomerTO>();
//& other such mapping
});
_mapper = config.CreateMapper();
}
public CustomerTO Map(Customer customerEntity)
{
var customerTo= _mapper.Map<Customer,CustomerTO>(customerEntity);
return customerTo;
}
Now when I needed the mapping.
class DAL
{
public CustomerTO GetCustomers()
{
var customers= //LINQ To get customers
var customerTO = Mapping(customer);
return customerTO;
}
//However, this mapping glue in some internal class to retain SOLID principles
private CustomerTO Mapping(Customer custEntity)
{
var custTO = _appMapper.Map(custEntity);
var str = JsonConvert.Serialize(custTO.CustomerData);
custTO.CustomerData = JsonConvert.Deserialize(str);
return custTO;
}
}
That's it.
#Barry O'Kane - Sincere thanks for your inputs.
Points to be noted:-
I don't need to map manually any of the properites since the property name is same. Plus I am casting string to object. So no issues.
If you use .Map() for one property, then I found that I need to map each property else it gives default value of the data type.(Ex. for int it gives 0).
Yes. agreed there could be other method in Automapper which allows me specify that for a particulay property do this manual mapping & for rest use Automapping mechanism. But I am not sure on that.
Please feel free to improve this ans in any way.
Hope this helps :)
In the application I am busy writing, all my mapping destination objects derive from a base class like this:
public class CatalogObject<TObject>
{
TObject InnerObject { get; set; }
}
public class CatalogTable : CatalogObject<table>
{
public string Name { get; set; }
public int ObjectId { get; set; }
}
Now, after mapping a table object to a CatalogTable object, I want the InnerObject property of that destination to be a reference to the source table object.
You could do it with a Custom Resolver:
Mapper.CreateMap<Table, CatalogTable>()
.ForMember(dest => dest.InnerObject,
opt => opt.ResolveUsing<InnerObjectResolver>());
Where the resolver would look something like:
public class InnerObjectResolver : ValueResolver<Table, Table>
{
protected override Table ResolveCore(Table source)
{
return source;
}
}
Full details can be found in the custom resolver documentation.
You might also be able to do it directly, but I haven't tried that. Something like this maybe:
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.InnerObject, opt => opt.MapFrom(src => src));
I'm having some trouble trying to map these two classes (Control -> ControlVM)
public class Control
{
public IEnumerable<FieldType> Fields { get; set; }
public class FieldType
{
//Some properties
}
}
public class ControlVM
{
public FieldList Fields { get; set; }
public class FieldList
{
public IEnumerable<FieldType> Items { get; set; }
}
public class FieldType
{
//Properties I'd like to map from the original
}
}
I tried with opt.ResolveUsing(src => new { Items = src.Fields }) but apparently AutoMapper cannot resolve the anonymous type. Also tried extending ValueResolver, but didn't work either.
NOTE: This VM is later used in a WebApi, and JSON.NET needs a wrapper around the collection to properly deserialize it. So removing the wrapper is not a solution.
NOTE2: I'm also doing Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>(), so the problem isn't there.
This works for me:
Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>();
// Map between IEnumerable<Control.FieldType> and ControlVM.FieldList:
Mapper.CreateMap<IEnumerable<Control.FieldType>, ControlVM.FieldList>()
.ForMember(dest => dest.Items, opt => opt.MapFrom(src => src));
Mapper.CreateMap<Control, ControlVM>();
Update: Here's how to map the other way:
Mapper.CreateMap<ControlVM.FieldType, Control.FieldType>();
Mapper.CreateMap<ControlVM, Control>()
.ForMember(dest => dest.Fields, opt => opt.MapFrom(src => src.Fields.Items));