1

How to map List of anonymous to List of T using AutoMapper?

For example:

class Test{
  public string a1{get;set]}
  public string a2{get;set;}
}

//....Entity Framework 4.3.1
var t=from z in db select {z.a1,z.a2};

var tmp=AutoMapper.Mapper.DynamicMap<List<Test>>(t);

But tmp always is empty

How to fix it?

2 Answers2

1

You will need to call t.ToList() to execute the query first

var tmp=AutoMapper.Mapper.DynamicMap<List<Test>>(t.ToList());
bhiku
  • 128
  • 9
  • daft question probably, but does calling t.ToList() return the expected number of items? – bhiku Apr 25 '12 at 15:22
  • see gist https://gist.github.com/2491229. It doesn't use Automapper but uses LINQ to achieve the same result. Hope this helps – bhiku Apr 25 '12 at 16:49
  • It's good but AutoMapper allows create calculated field and custom casting and... – user1356462 Apr 25 '12 at 18:21
  • Automapper has an open issue - https://github.com/AutoMapper/AutoMapper/issues/148 related to dynamic mapping for collection and arrays. I have updated the gist - https://gist.github.com/2491229 with an alternate use of AutoMapper dynamic mapping. Hope you find it useful – bhiku Apr 25 '12 at 22:03
0

how about you change

var t=from z in db select new Test
                          {
                             a1 = z.a1,
                             a2 = z.a2
                           }

EDIT to allow mapping to dynamic types , you can refer to existing post

Community
  • 1
  • 1
Turbot
  • 5,095
  • 1
  • 22
  • 30