Ivan Debono
Ivan Debono

Reputation: 941

Ignore navigation property when mapping in Automapper

Having these 2 classes as an example:

public class Product
{
    public int Id {get; set;}
    public int CategoryId {get; set;}
}

public class ProductDTO
{
    public int Id {get; set;}
    public int CategoryId {get; set;}
    public Category Category {get; set;}
}

How can I ignore ProductDTO.Category when mapping bidrectionally?

Upvotes: 3

Views: 1066

Answers (1)

hutchonoid
hutchonoid

Reputation: 33306

Assuming that you mean bi-directional i.e. both classes have a Category member that you want to ignore you can use .ReverseMap().

Mappings

Mapper.CreateMap<Product, ProductDTO>()                
                .ForMember(dest => dest.Category, opt => opt.Ignore()).ReverseMap();

Example Models

public class Product
    {
        public int Id {get; set;}
        public int CategoryId {get; set;}
        public Category Category {get; set;}
    }

    public class ProductDTO
    {
        public int Id {get; set;}
        public int CategoryId {get; set;}
        public Category Category {get; set;}
    }

    public class Category
    {

    }

Working Fiddle

Upvotes: 2

Related Questions