Reputation: 37780
Here's the simple hierarchy:
abstract class Base
{
public int Id { get; set; }
}
class Derived : Base
{
public string Name { get; set; }
}
I need to clone Derived
instances, but I want to skip Id
values. So, I'm configuring mapper this way:
Mapper
.CreateMap<Base, Base>()
.Include<Derived, Derived>()
.ForMember(_ => _.Id, expression => expression.Ignore());
var original = new Derived
{
Id = 1,
Name = "John"
};
var clone = Mapper.Map<Derived>(original);
Console.WriteLine(clone.Id == 0); // writes 'False'
Regardless of ForMember
call, the value of Id
is mapped.
This configuration:
Mapper
.CreateMap<Derived, Derived>()
.ForMember(_ => _.Id, expression => expression.Ignore());
works as expected, but this is not an option, because it needs to set ForMember
for each derived type.
Automapper version is 2.2.1. What am I doing wrong?
Upvotes: 0
Views: 990
Reputation: 2551
Have you tried to Ignore
also the Id
property on the base class mapping?
Mapper
.CreateMap<Base, Base>()
.ForMember(_ => _.Id, expression => expression.Ignore())
.Include<Derived, Derived>()
.ForMember(_ => _.Id, expression => expression.Ignore());
[...]convention has a higher priority that Ignored properties in the base class mappings[...]
https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance
Upvotes: 1