在Automapper中映射时忽略导航属性

时间:2014-11-21 06:44:20

标签: c# automapper

以这两个类为例:

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;}
}

在双向投标时如何忽略ProductDTO.Category

1 个答案:

答案 0 :(得分:2)

假设您的意思是双向的,即两个类都有一个您想忽略的Category成员,您可以使用.ReverseMap()

<强>映射

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

示例模型

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