如何使用Automapper 5



我是AutoMapper的新手。使用以下链接,我试图在行动中理解它。

  • http://automapper.org/
  • https://lostechies.com/jimmybogard/2016/01/21/removing-the-patatic-patic-api-from-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
    }
}

错误-Cannot隐式将类型System.Collections.generic.list'转换为 'System.Collections.generic.Ienumerable'。存在明确的转换(您是否缺少演员?)

如何将List<Customer>映射到List<CustomerTO>

请注意,在Customer中,我具有 string类型的属性,带有名称 Custname的属性,而 CustomerTO我的属性具有 object的名称 CustData。那么如何映射此不同的名称属性?

谢谢。

在要映射的类型中使用相同的属性名称是美国自动应用程序的最简单方法。这样,您现在拥有的配置就可以了。

但是,在您不这样做的情况下,您需要指定如何映射属性,如下所示

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

我假设您想将CustName直接映射到上面的CustData,这将正常工作。

相关内容

  • 没有找到相关文章

最新更新