开发者

How do I call different mapping strategy for same type in AutoMapper?

I have a customer class & I'd like to have the customer emails field display in CSV format for an admin list view. When the edit view shows, I'd like to have the view show emails in a textbox split with a newline character feed.

I don't want to have 2 different classes for each view just use the same, with the first using IEnumerable<T> to display the list. My class is quite large and I don't want to have 2 separate view classes to manage.

The ideal goal would be to have 2 different AutoMapper mappings 1 for each different mapping scenario rather than just being limited to the the one created using CreateMap at bootstrap stage. How do I 开发者_运维知识库achieve this? Effectively I'd like to switch the mapping strategy depending on where I am in the code.


Ideally you would use two different View Models and map the source to the desired destination. However, if you don't want to go this route one option would be to create a view model that has two readonly properties.

public class SomeClassViewModel
{
    public string FirstName { get; set;}

    public string LastName { get; set; }

    public string Emails { get; set; }

    public string EmailsCSV
    {
        get
        {
            var csv = Emails;
            //Do CSV transform here
            return csv;
        }
    }

    public string EmailsCRLF
    {
        get
        {
            var crlf = Emails;
            //Do crlf transform here
            return crlf;
        }
    }

}

Again, ideally you would want to stick with the rule of one model per view. That doesn't mean you are required to write an entirely new view for each model, there's always inheritance.

MyViewModelA : MyViewModelBase
MyViewModelB : MyViewModelBase
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜