Inheritance related question - c#

I have a class Base. A and B extend Base. There is also a class Relationship which contains two Base objects (source, target). Is it possible to determine whether source/target is an A or B instance?
Thanks.
Christian
PS:
Here is a little add on. I am using automapper and I would like to map the type of source/target to a string called 'Type' - GetType did not work (actually it works -s ee my comments - is and as are good solutions too):
Mapper.CreateMap<Item, ItemViewModel>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.ItemName == null ? "" : src.ItemName.Name))
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.GetType().ToString()));
How can I use is/as in this scenario?

Yup:
if (source is A)
if (source is B)
etc
or:
A sourceA = source as A;
if (sourceA != null)
{
...
}
etc
See this question for more guidance - and there are plenty of other similar ones, too.

yes.
if (source is B)...

Using the is operator? :)

Related

Automapper - how to map two complex collections to one destination collection object

I have the two distinct objects and would like to map them to one destination object. The source objects are complex objects which contain multiple child objects which would also need to be mapped. I've tried something similar to the below example but as expected, the last mapping will overwrite any previous mapping.
CreateMap<sourceObject, destinationObject>()
.ForMember(d => d.Addresses, o => o.MapFrom(s => s.Addresses.MainAddresses))
.ForMember(d => d.Addresses, o => o.MapFrom(s => s.Addresses.SomeOtherAddresses))
I suppose I'm looking for something like a MapFrom().AndThenMapFrom() method (a join or union type transformation).
I have used a custom value resolver to get around the issue but this seems to defeat the purpose of automapper in my eyes. Any other suggestions would be welcomed.
If you want to concatenate in Addresses results of mappings (MainAddresses to Addresses and SomeOtherAddresses to Addresses), one solution would be
CreateMap<sourceObject, destinationObject>()
.ForMember(
d => d.Addresses,
o => o.MapFrom(
s => s.Addresses.MainAddresses
.Cast<object>()
.Concat(s.Addresses.SomeOtherAddresses)))
or
CreateMap<sourceObject, destinationObject>()
.ForMember(
d => d.Addresses,
o => o.MapFrom(
s => s.Addresses.MainAddresses
.Cast<IAddress>()
.Concat(s.Addresses.SomeOtherAddresses)))
if objects in MainAddresses and SomeOtherAddresses realize IAddress interface.
Another solution is to do it in Before/AfterMap method
CreateMap<sourceObject, destinationObject>()
.BeforeMap(
(s, d, c) =>
{
var mainAddresses = c.Mapper.Map<IEnumerable<Address>>(s.Addresses.MainAddresses);
var someOtherAddresses = c.Mapper.Map<IEnumerable<Address>>(s.Addresses.SomeOtherAddresses);
d.Addresses = mainAddresses
.Concat(someOtherAddresses)
.ToArray();
})
.ForMember(d => d.Addresses, o => o.Ignore());
In this case mapping for Addresses should be ignored, because we do it "manually" in BeforeMap. Unfortunately both solutions are not elegant as most of simple automapper rules.

Automapper for member condition

I am using auto mapper 6.1 and I want to map some values from one object to another, but there is a condition that those values can not be null and not all object properties are supposed to be mapped if so I could easily use ForAllMembers conditions. What I am trying to do is:
config.CreateMap<ClassA, ClassB>()
.ForMember(x => x.Branch, opt => opt.Condition(src => src.Branch != null),
cd => cd.MapFrom(map => map.Branch ?? x.Branch))
Also tried
config.CreateMap<ClassA, ClassB>().ForMember(x => x.Branch, cd => {
cd.Condition(map => map.Branch != null);
cd.MapFrom(map => map.Branch);
})
In another words for every property I define in auto mapper configuration I want to check if its null, and if it is null leave value from x.
Call for such auto mapper configuration would look like:
ClassA platform = Mapper.Map<ClassA>(classB);
If I've understood correctly, it may be simpler than you think. The opt.Condition is not necessary because the condition is already being taken care of in MapFrom.
I think the following should achieve what you want: it will map Branch if it's not null. If Branch (from the source) is null, then it will set the destination to string.Empty.
config.CreateMap<ClassA, Class>()
.ForMember(x => x.Branch, cd => cd.MapFrom(map => map.Branch ?? string.Empty));
And if you need to use another property from x instead of string.Empty, then you can write:
config.CreateMap<ClassA, Class>()
.ForMember(x => x.Branch, cd => cd.MapFrom(map => map.Branch ?? x.AnotherProperty));
If you want to implement complex logic but keep the mapping neat, you can extract your logic into a separate method. For instance:
config.CreateMap<ClassA, Class>()
.ForMember(x => x.Branch, cd => cd.MapFrom(map => MyCustomMapping(map)));
private static string MyCustomMapping(ClassA source)
{
if (source.Branch == null)
{
// Do something
}
else
{
return source.Branch;
}
}
You don't need the MapFrom, but you need a PreCondition instead. See here.

Automapper.mapper.map doesn't work but mapper.dynamicmap work

First of all, sorry for my bad english! I'm french.
I tried to find on google but without any result so, this is my automapper configuration :
public void CreateMap(IMapperConfiguration cfg)
{
cfg.CreateMap<GroupeApplication, GroupeApplicationContract>();
cfg.CreateMap<Application, ApplicationContract>()
.ForMember(d => d.GroupeApplicationId, o => o.MapFrom(s => s.GroupeApplication != null ? s.GroupeApplication.Id : Guid.Empty));
cfg.CreateMap<Application, ApplicationWithAscendantContract>()
.ForMember(d => d.GroupeApplication, o => o.MapFrom(s => Mapper.Map<GroupeApplicationContract>(s.GroupeApplication)));
cfg.CreateMap<GroupeApplication, GroupeApplicationWithDescendantContract>()
.ForMember(d => d.Applications, o => o.MapFrom(s => Mapper.Map<List<ApplicationContract>>(s.Applications)));
Mapper.AssertConfigurationIsValid();
}
In fact, groupeapplication has list of application, and Mapper.Map failed when it try to map my applications collection... this is the error message :
Missing type map configuration or unsupported mapping.
Mapping types:
Application -> ApplicationContract
UGO.Distribution.Domain.Application -> UGO.Distribution.Shared.Contracts.ApplicationContract
Destination path:
List`1[0]
Source value:
UGO.Distribution.Domain.Application
If I replace the last config with this it works (I replace Mapper.Map by Mapper.DynamicMap) :
cfg.CreateMap<GroupeApplication, GroupeApplicationWithDescendantContract>()
.ForMember(d => d.Applications, o => o.MapFrom(s => Mapper.DynamicMap<List<ApplicationContract>>(s.Applications)));
I could be satisfied, but that is not for me is that this method is deprecated in automapper 4.0.3 !!
Is there any explanation or a better solution for this problem?
Instead of putting ForMember(...), try:
ForMember<ObjectThatYouWantMap>(...);

How to ignore all destination members, except the ones that are mapped? [duplicate]

This question already has answers here:
AutoMapper: "Ignore the rest"?
(20 answers)
Closed 6 years ago.
Is there a way to do this? We have a SummaryDto that maps from three different types, and when we create a map for each type, props that are not mapped are throwing an error. There are about 35 attributes on the summary dto. To use Ignore() option on each one is just too much trouble. Is there a global ignore? Something like
CreateMap<Source,Target>()
.IgnoreAllUnmapped();
This is working for me:
public static class MappingExpressionExtensions
{
public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
{
expression.ForAllMembers(opt => opt.Ignore());
return expression;
}
}
Because ForAllMembers returns void, calling ForAllMembers(o => o.Ignore()) without this extension method wouldn't work. We want to keep the mapping expression available to enable the subsequent mappings:
CreateMap<Source, Destination>()
.IgnoreAllUnmapped()
.ForMember(d => d.Text, o => o.MapFrom(s => s.Name))
.ForMember(d => d.Value, o => o.MapFrom(s => s.Id));
I struggled with this one for quite a while too, or at least a problem similar to this. I had a class with a lot of properties on it (about 30) and I only wanted to map about 4 of them. It seems crazy to add 26 ignore statements (especially when it means that future changes to the class will mean having to update them!)
I finally found that I could tell AutoMapper to ignore everything, and then explicitly add the ones that I did want.
// Create a map, store a reference to it in a local variable
var map = CreateMap<Source,Target>();
// Ignore all members
map.ForAllMembers(opt => opt.Ignore());
// Add mapping for P1
map.ForMember(dest => dest.P1, opt => opt.MapFrom( src => src.P1));
// Add other mappings...
map.ForMember(dest => dest.P2, opt => opt.MapFrom( src => src.P2));
map.ForMember(dest => dest.P3, opt => opt.MapFrom( src => src.P3));
map.ForMember(dest => dest.P4, opt => opt.MapFrom( src => src.P4));
You'd be forgiven for thinking that you could just do this (but don't because it wont compile):
// This won't compile
CreateMap<Source,Target>()
.ForAllMembers(opt => opt.Ignore())
.ForMember(dest => dest.P1, opt => opt.MapFrom( src => src.P1));
The reason why this doesn't work is that the ForAllMembers() method doesn't support the fluent style of chaining (at least in the current version 2.0).
The good news is that the non-chaining version does indeed work. The one caveat of course is that you need to explicitly tell AutoMapper which members to map. I haven't yet found an easy way to have it both ways so that you can still use the implied mappings and ignore the broken ones.
To avoid having to explicitly specify the mapped properties, you can use IgnoreAllNonExisting. It ignores any destination properties that don't have mapped source properties.
Try to use .ConvertUsing() in your case, e.g.
CreateMap<Source,Target>()
.ConvertUsing(converter=> new Target(){
P1 = converter.P1,
....
});
So, you can describe all properties what you want to have in your object, other will be ignored.
Extension method which allows fluent syntax for the ForAllMembers method:
public static IMappingExpression<TSource, TDestination> IgnoreAllMembers<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> expression
)
{
expression.ForAllMembers(opt => opt.Ignore());
return expression;
}
Usage:
The call to IgnoreAllMembers must be before the call to ForMember.
CreateMap<LocationRevision, Dto.LocationAddressMap>()
.IgnoreAllMembers()
.ForMember(m => m.LocationId, opt => opt.MapFrom(src => src.Id))
;

AutoMapper - setting destination string to null actually makes it string.Empty

With the following mapping:
Mapper.CreateMap<ObjectA, ObjectB>()
.ForMember(dest => dest.SomeStringProperty, opt => opt.MapFrom(src => null))
SomeStringProperty is now empty string not null (as I would expect)
Is this a bug? How can I get it to actually be null?
I see that opt.Ignore() will make it null but I actually want to do a conditional null like the following and the above simplified bug(?) is preventing this
Mapper.CreateMap<ObjectA, ObjectB>()
.ForMember(dest => dest.SomeStringProperty, opt => opt.MapFrom(src => src.SomeOtherProp != null ? src.SomeOtherProp.Prop1 : null))
I found the setting after looking through the source code... Confirming that this is not a bug, but in fact a configurable setting.
When I configure my mappings..
Mapper.Initialize(x =>
{
x.AddProfile<UIProfile>();
x.AddProfile<InfrastructureProfile>();
x.AllowNullDestinationValues = true; // does exactly what it says (false by default)
});
you could define map for strings using
ITypeConverter<string, string>
and when you convert return null if null. I think it is by design that you get an empty string and I even find this natural and useful myself but I may of course be wrong ;)
I can provide more precise code than above upon request but reckon you know what you're doing.

Categories