2012-09-06 34 views
2

我有一個相當大的對象,有很多屬性。使用automapper忽略未使用的屬性

我正在使用Automapper映射到網格中的屬性。

只有少數屬性的需要映射其餘的也因爲它們不是在映射的時間後,曾經被忽略

是否有「忽略」所有這些屬性的或做的方式我需要爲每個屬性寫一個明確的「忽略」 - 請參閱下面的代碼。我希望能夠'.IgnoreAllNotUsed'而不必一個個地忽略。這可能嗎?

類從另一個類繼承,但大多數的屬性是實際的類本身 link to picture of code enter image description here

enter image description here

回答

3

您可以使用此擴展方法:

public static void ForAllUnmappedMembers<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> mapping, 
    Action<IMemberConfigurationExpression<TSource>> memberOptions) 
{ 
    var typeMap = Mapper.FindTypeMapFor<TSource, TDestination>(); 
    foreach(var memberName in typeMap.GetUnmappedPropertyNames()) 
     mapping.ForMember(memberName, memberOptions); 
} 

使用它像這樣:

Mapper.CreateMap<Source, Destination>() 
     .ForMember(...) 
     .ForAllUnmappedMembers(o => o.Ignore()); 

我沒有測試過它,但它應該可以工作。

6

只是忽略所有屬性,然後指定ForMember。這裏是例子:

var mapping = Mapper.CreateMap<Source, Destination>(); 
mapping.ForAllMembers(opt=>opt.Ignore()); 
mapping.ForMember(...) 
     .ForMember(...); 
+0

希望我可以標記超過1作爲答案。不管怎麼說,還是要謝謝你 – kurasa