0

我是 Automapper 的新手。通过下面的链接,我正在尝试理解它。

我正在使用它的 Automapper v 5.2.0

这是我的东西。 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

    }
}

错误 - 无法将类型 System.Collections.Generic.List' 隐式转换为 'System.Collections.Generic.IEnumerable'。存在显式转换(您是否缺少演员表?)

我如何映射List<Customer>List<CustomerTO>

请注意,在Customer我的属性类型string为 nameCustname时,CustomerTO我的属性名称CustData为 type object。那么如何映射这个不同的名称属性呢?

谢谢。

4

1 回答 1

1

对要映射的类型中的属性使用相同的名称是我们 AutoMapper 最简单的方法。这样你现在的配置就可以工作了。

但是,如果您不这样做,则需要指定如何映射属性,如下所示

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

我假设你想直接映射CustNameCustData上面,这会很好。

于 2017-02-21T10:32:32.243 回答