How to use Automapper 5?

强颜欢笑 提交于 2019-12-12 01:46:21

问题


I am new to Automapper. With below links, I am trying to understand it in action.

  • http://automapper.org/
  • https://lostechies.com/jimmybogard/2016/01/21/removing-the-static-api-from-automapper/

I am using its Automapper v 5.2.0

Here is my stuff. https://codepaste.net/xph2oa

class Program
{
    static void Main(string[] args)
    {
        //PLEASE IGNORE NAMING CONVENTIONS FOR NOW.Sorry!!
        //on Startup 
        AppMapper mapperObj = new AppMapper();
        mapperObj.Mapping();

        DAL obj = new DAL();
        var customer = obj.AddCustomers();


    }
}

class Customer
{
    public int CustomerId { get; set; }

    public string CustName { get; set; }
}


class CustomerTO
{
    public int CustId { get; set; }

    public object CustData { get; set; }
}


class AppMapper
{
    public void Mapping()
    {
        var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<Customer, CustomerTO>();
                    });

        IMapper mapper = config.CreateMapper();

    }
}

class DAL
{
    public IEnumerable<CustomerTO> AddCustomers()
    {
        List<Customer> customers = new List<Customer>();
        customers.Add(new Customer() { CustName = "Ram", CustomerId = 1 });
        customers.Add(new Customer() { CustName = "Shyam", CustomerId = 2 });
        customers.Add(new Customer() { CustName = "Mohan", CustomerId = 3 });
        customers.Add(new Customer() { CustName = "Steve", CustomerId = 4 });
        customers.Add(new Customer() { CustName = "John", CustomerId = 5 });

        return customers;   //throws error

    }
}

Error -Cannot implicitly convert type System.Collections.Generic.List' to ' System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

How do I map List<Customer> to List<CustomerTO> ?

Please note, in Customer I have property of type string with name Custname while CustomerTO I have the property with name CustData of type object. So how do I map this different name property?

Thanks.


回答1:


Using the same names for properties in the types to be mapped is the simplest way to us AutoMapper. That way the config you have now will work.

However, in the case where you don't do that you need to specify how the properties are to be mapped, as follows

cfg.CreateMap<Customer, CustomerTO>()
.ForMember(dto => dto.CustData, opt => opt.MapFrom(entity => entity.CustName))
.ForMember(dto => dto.CustId, opt => opt.MapFrom(entity, entity.CustomerId));

I'm assuming that you want to straight map CustName to CustData above, and this will work fine.



来源:https://stackoverflow.com/questions/42364647/how-to-use-automapper-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!