2017-02-21 37 views
0

我是Automapper的新手。通过下面的链接,我试图在行动中理解它。如何使用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 

    } 
} 

错误-Cannot隐式转换类型System.Collections.Generic.List”到 'System.Collections.Generic.IEnumerable'。存在明确的转换(您是否缺少演员?)

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

请注意,在Customerstring类型的属性与名称CustnameCustomerTO我有object类型的名称CustData财产。 那么我该如何映射这个不同的名称属性?

感谢。

+0

检查[this](http://stackoverflow.com/questions/37348788/automapper-5-0-global-configuration)我认为它会帮助你。但我不知道你是否可以从'string'映射到'object' –

+0

你看过维基?它具有最新的文档,而不是我的博客,它可能会过时(例如,静态API仍然存在,并且会存在)。 –

+0

@JimmyBogard,感谢您的博客。你的博客+其他一些链接足以让我开始。我没有检查到维基。 –

回答

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情况上面,这将工作正常。

+0

假设我在Customer&CustomerTO中有10多个房产。 9个属性具有相同的名称,但1个属性名称和类型不同。在这种情况下,我需要写.ForMember <> 10次 –

+0

不,您只需要为名称不同的成员指定。 –

+0

您可以在DAL方法中检查更新后的帖子,发现构建错误 –