简体   繁体   中英

AutoMapper Flattening without the name convention

I'm trying to flatten my Domain model into the Contract type

This is my Model:

public interface IPrice
{
    IItem Item { get; set; }
    Money Money {get; set;}
}

public interface IItem
{
    IItemHeader Header { get; set; }
}

public interface IItemHeader
{
    string Name{ get; set; }
}

and this is my Contract:

public class Price
{
  public string Name{ get; set; }  
}

Now, I know that if i will change the contract Name field to ItemHeaderName AutoMapper will handle that and will set the correct value when I map between IPrice and Price. but what if I don't like that name (ie ItemHeaderName) and insist on using " Name " instead? is there is any alternative?

If you call it just Name, then you need MapFrom. You can also have a custom naming convention if the default one doesn't work for you.

We need to do something like that:

 CreateMap<Contract.Entities.Price, Model.Entities.IPrice>().
            ReverseMap().
            ForMember(model => model.Name, model => model.MapFrom(src => src.Item.Header.Name)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM