2014-11-21 202 views
3

有了這2類爲例:忽略導航屬性時,映射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 bidrectionally映射時?

回答

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