I'm new to AutoMapper and have couple of questions regarding datatable to object mapping. I have sqlquery code and sql result. I want to do object to object map with automapper. any help's?
Asked
Active
Viewed 6,329 times
3 Answers
3
I guess it could go something like this (broad lines):
AutoMapper.Mapper.CreateMap<DataSet, CompanyModel>()
.ForMember(m => m.Company, opt => opt.MapFrom(r => r.Tables[0].Columns["Company"]))
.ForMember(m => m.Customers, opt => opt.MapFrom(r => r.Tables[0].Columns["Customers"]))
.ForMember(m => m.Amount, opt => opt.MapFrom(r => Double.Parse(r.Tables[0].Columns["Amount"]));
and then
Mapper.Map<List<CompanyModel>>(ds);
Providing more details (code) would probably result in more precise answers.

Alexandru Marculescu
- 5,569
- 6
- 34
- 50
-
I tried your code but Not WorkingError:An exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll but was not handled in user code. – Sai Kumar Oct 12 '16 at 06:30
2
Look here Convert DataRow to Object with AutoMapper
For now I did this based on above, so far I have only tested with flat DTO with Primitive types:
public class CustomResolver : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
return source.New(Convert.ChangeType((source.Context.SourceValue as DataRow)[source.Context.MemberName], source.Context.DestinationType));
}
}
public static class DtoTransformDataTable<T> where T : new()
{
public static IEnumerable<T> JustDoIt(DataTable dt)
{
Mapper.CreateMap<DataRow, T>().ForAllMembers(m => m.ResolveUsing<CustomResolver>());
var listOfT = new List<T>();
foreach (var item in dt.Rows) //Use LINQ to concise
{
var dest = Mapper.Map<T>(item);
listOfT.Add(dest);
}
return listOfT;
}
}

Community
- 1
- 1

Manas Padhi
- 31
- 4
-
Don't think that works with AutoMapper 5 - the IValueResolver interface has changed - https://github.com/AutoMapper/AutoMapper/wiki/5.0-Upgrade-Guide – David Gardiner Feb 02 '17 at 03:38
0
I don't think this is supported by Automapper out of the box if you are using plain untyped DataTables
/DataSets
.
However, if you create a typed DataTable
/DataSet
then things should work better. A typed DataSet
gives your table rows properties for each column and should be easier to use with AutoMapper.
I haven't used typed DataSets
in years, but they are still supported in .Net. Look here for some information on how to set them up.

Rune Grimstad
- 35,612
- 10
- 61
- 76