With AutoMapper, can I override the resolved type for a property? For example, given these classes:
public class Parent
{
public Child Value { get; set; }
}
public class Child { ... }
public class DerivedChild : Child { ... }
Can I configure AutoMapper to automap the Child Value property with a DerivedChild instance? The hypothetical mapping would look something like this:
map.CreateMap<ChildEntity, DerivedChild>();
map.CreateMap<ParentEntity, Parent>()
.ForMember(p => p.Value, p => p.UseDestinationType<DerivedChild>());
(I'm projecting from LINQ entities. The closest I could find is using a custom type converter, but it looks like I'd need to override the entire mapping.)
Here is one way to do it:
map.CreateMap<ChildEntity, DerivedChild>();
map.CreateMap<ParentEntity, Parent>()
.ForMember(
x => x.Value,
opt => opt.ResolveUsing(
rr => map.Map<DerivedChild>(((ParentEntity)rr.Context.SourceValue).Value)));
ResolveUsing allows to specify custom logic for mapping the value.
The custom logic that is used here is actually calling map.Map to map to DerivedChild.
You may re-assign new object manually after mapping:
Mapper.CreateMap<ParentEntity, Parent>()
.AfterMap((src, dest) => dest.Value = new DerivedChild(){...});
or even re-map it:
.AfterMap((src, dest) => dest.Value = Mapper.Map<DerivedChild>(dest.Value));
Related
I have a lot of classes to map from IDataReader like this:
class Dest
{
public string Field1;
public string Field2;
public string Field3;
}
...
public DestProfile
{
CreateMap<IDataReader, Dest>()
.ForMember(d => d.Field1, opt => opt.MapFrom(/*Do some custom convertion here*/)
.ForAllOtherMembers(/*Do default convention-based mapping for all other members/*)
}
So i'd like to perform custom convertion on selected fields and do default mapping without explicitly coding.
Question looks very common, but I didn't find how to achieve this.
So the most straightforward way is to write like this:
.ForAllOtherMembers(opt => opt.MapFrom(src => src[opt.DestinationMember.Name]))
But there are some caveats. For example
.IncludeBase<IDataReader, Base>()
.ForAllOtherMembers(opt => opt.MapFrom(src => src[opt.DestinationMember.Name]))
Here ForAllOtherMembers will override your base class definition.
I'm using Automapper and need to know whether I can map a source variable to a nested member variable?
This is the source I want to map from
public class source
{
public string name;
}
This is the destination - I need the name variable assigned to the Nested.Name member
public class Destination
{
public Nested info;
}
public class Nested
{
public string name;
}
Any help greatly appreciated.
Ron.
ForPath would do the trick
CreateMap<source, Destination>()
.ForPath(d => d.info.name, c => c.MapFrom(src => src.name));
Something like this should do the trick, although you might run into an uninitialized dst.info
CreateMap<source, Destination>()
//reegular mapping here
.ForMember(dst => dst.foo, c => c.MapFrom(src => src.otherfoo))
//AfterMap to bind your properties
.AfterMap((src, dst) => { dst.info.name = src.name; });
I have the following map rules:
CreateMap<ViewModels.ApplicationDriverAccidentFormVM, ApplicationDriverAccidentDomain>();
then I want to map ViewModels.ApplicationDriverFormVM to ApplicationDriverDomain, both are have Accidents property, which are appropriate collections for each type.
public class ApplicationDriverDomain
{
public List<ApplicationDriverAccidentDomain> Accidents { get; set; }
}
public class ApplicationDriverFormVM
{
public List<ApplicationDriverAccidentFormVM> Accidents { get; set; }
}
And I want to exclude (not map) all records, which are not satisfied some conditions
I try to write the following code:
CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>()
.ForMember(dest => dest.Accidents, opt => opt.MapFrom(src => GetNotNullFromCollection(src.Accidents)))
where GetNotNullFromCollection is:
List<object> GetNotNullFromCollection(object input)
{
List<object> output = new List<object>();
foreach (var item in (List<object>)input)
{
if (!Utils.IsAllNull(item))
output.Add(item);
}
return output;
}
but it says me:
Unable to cast object of type
'System.Collections.Generic.List1[Web.ViewModels.ApplicationDriverAccidentFormVM]'
to type 'System.Collections.Generic.List1[System.Object]'.
Why and how to do it?
your method GetNotNullFromCollection receives an object but you are passing it a list.
Anyway, I would recommend using Generics instead of objects.
I solved it by the following way:
CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>().ForMember(dest => dest.Accidents, opt => opt.MapFrom(src => src.Accidents.Where(o => !Utils.IsAllNull(o))))
I have following structure for tables. The two tables have a lot of common properties over 20 im just listing a two. Also I have 10 tables similar to this. This is how the tables are in the database. There is over 10 concrete tables with similar properties and are not connected to each other in any way. I am using POCO generator to generate the classes from my database.
public class A
{
public string name {get;set;}
public string address {get;set;}
public string AId {get;set;}
}
public class B
{
public string name {get;set;}
public string address {get;set;}
public string BId {get;set;}
}
I have following viewModels:
public class BaseViewModel
{
public string Fullname {get;set;}
public string Fulladdress {get;set;}
}
public class AviewModel : BaseViewModel
{
public string AId {get;set;}
}
public class BViewModel : BaseViewModel
{
public string BId {get;set;}
}
when I create mapping i have to repeat all this for each viewModel that I have created.
config.CreateMap<A, AviewModel>()
.ForMember(dest => Fulladdress, opt => opt.MapFrom(src =>.address))
.ForMember(dest => Fullname, opt => opt.MapFrom(src =>.name)).ReverseMap();
config.CreateMap<B, BviewModel>()
.ForMember(dest => Fulladdress, opt => opt.MapFrom(src =>.address))
.ForMember(dest => Fullname, opt => opt.MapFrom(src =>.name)).ReverseMap();
Is it possible to reduce the repetitive mappings that I might potentially have to do ?
You can move the common mapping code to a helper generic method. You will constrain the TDestination type to be a class derived from BaseViewModel, thus allowing to access the destination members in ForMember method. And for source mapping you will use the MapFrom overload accepting string property name:
public static class CommonMappings
{
public static IMappingExpression<TSource, TDestination> MapToBaseViewModel<TSource, TDestination>(this IMappingExpression<TSource, TDestination> map)
where TDestination : BaseViewModel
{
return map
.ForMember(dest => dest.Fulladdress, opt => opt.MapFrom("address"))
.ForMember(dest => dest.Fullname, opt => opt.MapFrom("name"));
}
}
Then you can use it like this:
config.CreateMap<A, AViewModel>()
.MapToBaseViewModel()
// ... specific mappings
.ReverseMap();
config.CreateMap<B, BViewModel>()
.MapToBaseViewModel()
// ... specific mappings
.ReverseMap();
Update: It turns out that automatic reverse mapping in the latest at this time AutoMapper 6.1.1 works for the lambda overload of MapFrom, but not for the string overload (in AutoMapper 5 it doesn't work at all). So until it gets fixed, you can use the following MapFrom(string) replacement:
public static class AMExtensions
{
public static void From<TSource, TDestination, TMember>(this IMemberConfigurationExpression<TSource, TDestination, TMember> opt, string name)
{
var parameter = Expression.Parameter(typeof(TSource), "src");
var body = Expression.PropertyOrField(parameter, name);
var selector = Expression.Lambda(body, parameter);
opt.MapFrom((dynamic)selector);
}
}
Which means you'll need to replace MapFrom calls in the original solution with From, because we can't give the extension method the same name since it has less priority than the concrete interface method.
Probably too much effort compared to base class approach. But useful in case you can't control the design of the entity classes.
You need a base class for the source classes. You create a map between the base source class and the destination class. You include that map in the map for the derived classes. That would allow you to reuse the configuration. The docs. For simple cases you can use As instead of Include.
You set an attribute on properties on your models.
This contains the name of the property it maps from on a source object.
Then you make a generic method that accepts the target object and source object, that finds the customattribute on the property where the attribute was set, and the property on the target object (or vice versa) and then sets the value.
You can even handle nested objects by asking if its a class property or not.
Is it possible to tell Fluent NHibernate not to map a property in a SubClassMap which is defined in it's parent's ClassMap? So:
public class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
this.Map(x => x.Id);
this.HasManyToMany(x => x.Somethings)
.Table("ParentSomethings")
.ParentKeyColumn("ParentId")
.ChildKeyColumn("SomethingId");
this.DiscriminateSubClassesOn("Foo");
}
}
public class ChildMap : SubclassMap<Child> // with Child : Parent
{
this.DiscriminatorValue("Child");
this.DontMap(x => x.Somethings); // fictional method
}
If you need to do this, your map are wrong, you need to create a ClassMap to Parent, and don't map this property "something", and create two differents mappings for children, one that contains "something" property and one that does not contain.