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
  • 1
    does it work without dynamicmapping? something like Mapper.CreateMap<db.test, Test>(); var tmp = Mapper.Map<IEnumerable<db.test>, List<Test>>(t); Commented Apr 25, 2012 at 14:55
  • var t is IQueriable of anonymous class and cannot use with this form (db.test) Commented Apr 25, 2012 at 15:06

2 Answers 2

1

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

var tmp=AutoMapper.Mapper.DynamicMap<List<Test>>(t.ToList());
Sign up to request clarification or add additional context in comments.

4 Comments

daft question probably, but does calling t.ToList() return the expected number of items?
see gist gist.github.com/2491229. It doesn't use Automapper but uses LINQ to achieve the same result. Hope this helps
It's good but AutoMapper allows create calculated field and custom casting and...
Automapper has an open issue - github.com/AutoMapper/AutoMapper/issues/148 related to dynamic mapping for collection and arrays. I have updated the gist - gist.github.com/2491229 with an alternate use of AutoMapper dynamic mapping. Hope you find it useful
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

2 Comments

Thanks. with this mode LINQ AutoMapper not needed but if LINQ query return extra fields than Test class, does't work. Is there any other Solution؟
@user1356462 : have you found out other the solution ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.