简体   繁体   中英

How to map two list with automapper?

I have two classes in the different location.

namespace IVR.MyEndpointApi.POCO
{
    [Table("MyServiceUrl")]
    public class MyURL
    {
        [Key]
        [Column("FacilityID")]
        public int FacilityId { get; set; }
        [Column("Url")]
        public string Url { get; set; }
    }
}

namespace OpsTools.Models
{
    public class MyServiceEndpoint
    {
        public int FacilityId { get; set; }
        public string Url { get; set; }
    }
}

In another method, I get the list and want to convert then return it as the desired type. I manually do it as below:

public List<MyServiceEndpoint> GetAllUrls()
{
    var management = GetMyEndpointManagement();
    var list = management.GetAllUrls(); 
    var urlList = new List<MyServiceEndpoint>();
    foreach (var item in list)
    {
        // the type of item is MyURL
        var MyUrl = new MyServiceEndpoint();
        myUrl.FacilityId = item.FacilityId;
        myUrl.Url = item.Url;
        urlList.Add(myUrl);
    }
    return urlList;
}

My question: can I apply AutoMapper to it?

EDIT:

I used the code:

        var myUrls = management.GetAllUrls();
        var urlList = new List<MyServiceEndpoint>();
        Mapper.CreateMap<MyServiceEndpoint, MyURL>();
        urlList = Mapper.Map<List<MyServiceEndpoint>, List<MyURL>>(myUrls);
        Mapper.AssertConfigurationIsValid();

However, it has the error:

Error   CS1503  Argument 1: cannot convert from 'System.Collections.Generic.List' to ....

Oops, come on. I change the order, then it works.

From

 urlList = Mapper.Map<List<MyServiceEndpoint>, List<MyURL>>(myUrls);

To

 urlList = Mapper.Map<List< List<MyURL>,MyServiceEndpoint>>(myUrls);

If you inspect the actual exception (you left the relevant part off), you'll see that Mapper.Map<TSource, TDestination>() tries to map from and to the wrong types.

The full error will read:

cannot convert from System.Collections.Generic.List<MyURL> to System.Collections.Generic.List<MyServiceEndpoint>

Which means that call will actually try to map from List<MyServiceEndpoint> , requiring an argument of that type, which your source list isn't.

Simply switch the types in the Map() call:

urlList = Mapper.Map<List<MyURL>, List<MyServiceEndpoint>>(myUrls);

Or remove the new list creation entirely, move the declaration and use type inference:

var urlList = Mapper.Map<List<MyServiceEndpoint>>(myUrls);

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