簡體   English   中英

AutoMapper:根據一些邏輯將目標屬性映射到其他源屬性/類型

[英]AutoMapper : Map a destination property to a different source property/type based on some logic

我想將Source對象映射到Destination對象,該對象具有一些額外的屬性,這些屬性不直接等同於源屬性。 考慮以下示例:

class Source { string ImageFilePath; }

class Destination { bool IsFileSelected; bool IsFileGif; }

IsFileGif的映射邏輯:

destinationObj.IsFileGif = Path.GetExtension(sourceObj.ImageFilePath) == ".gif" ? true : false;

IsFileSelected的映射邏輯:

destinationObj.IsFileSelected = string.IsNullOrEmpty(sourceObj.ImageFilePath) ? false : true;

另外,由於我的源代碼是IDataReader,所以我想知道如何將IDataReader對象的字段/列映射到我的Destination屬性。

我們可以使用內聯代碼來實現這一目標,還是必須使用Value Resolvers?

您是否嘗試過使用MapFrom方法?

Mapper.CreateMap<Source , Destination>()
 .ForMember(dest => dest.IsFileGif, opt => opt.MapFrom(src => Path.GetExtension(sourceObj.ImageFilePath) == ".gif")
 .ForMember(dest => dest.IsFileSelected, opt =>  opt.MapFrom(src => !string.IsNullOrEmpty(sourceObj.ImageFilePath));

關於IDataReader,我認為您應該在類之間進行映射(從源到目標),而不是從IDataReader到目標...

我想出了從IDataReader到Destination對象的映射:

Mapper.CreateMap<IDataReader, Destination>()
                    .ForMember(d => d.IsFileSelected,
                         o => o.MapFrom(s => !string.IsNullOrEmpty(s.GetValue(s.GetOrdinal("ImageFilePath")).ToString())))
                    .ForMember(d => d.IsFileGif,
                         o => o.MapFrom(s => Path.GetExtension(s.GetValue(s.GetOrdinal("ImageFilePath")).ToString()) == ".gif"));

如果有人驗證此代碼或建議是否存在更好的替代方法,將不勝感激。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM