Bart van den Burg
Bart van den Burg

Reputation: 2344

Automapper: ignore property on inherited class

I have a source class like this:

public class Basket {}

a target class like this:

public class BasketModel 
{
    public string Property { get; set; }
}

and a mapping like this:

Mapper.CreateMap<Basket, BasketModel>()
    .ForMember(x => x.Property, o => o.ResolveUsing(x => "anything"));

Now I've made the "Property" property in the original model virtual and created a new class that inherits from the model:

public class BasketModel 
{
    public virtual string Property { get; set; }
}
public class BasketModel2 : BasketModel
{
    public override string Property 
    { 
        get
        {
            return "some value";
        }
    }
}

I've updated the mapping as such:

Mapper.CreateMap<Basket, BasketModel>()
    .ForMember(x => x.Property, o => o.ResolveUsing(x => "anything"))
    .Include<Basket, BasketModel2>();

And created the mapping

Mapper.CreateMap<Basket, BasketModel2>()
    .ForMember(x => x.Property, o => o.Ignore());

Now when I try to map into BasketModel2, instead of null, the value of Property is "anything".

What am I missing here?

Upvotes: 2

Views: 341

Answers (1)

Bart van den Burg
Bart van den Burg

Reputation: 2344

Ok I think I had a brainfart when I wrote this code. model2.Property is never going to be null because it's a getter that always returns the same string. I have some refactoring to do, but AutoMapper was doing what it needs to do, I was just using it wrong.

Upvotes: 0

Related Questions