How to use AutoMapper to convert a DataTable to a List of custom objects

2,847 views
Skip to first unread message

hasi...@gmail.com

unread,
Aug 30, 2016, 10:16:38 PM8/30/16
to AutoMapper-users
I have data in a System.Data.DataTable instance. I want to get that data in to a collection of custom objects (List<MyCustomObject>). 

Please let me know if I can achieve that using AutoMapper, if so, how?

(The custom object will not have properties corresponding to each of the columns in the data table, but only a sub set of the columns.)

Jimmy Bogard

unread,
Aug 31, 2016, 11:23:36 AM8/31/16
to automapper-users
I don't think you can, I don't have built-in DataTable to custom object conversions.

--
You received this message because you are subscribed to the Google Groups "AutoMapper-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to automapper-users+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

epitka

unread,
Aug 31, 2016, 2:41:28 PM8/31/16
to AutoMapper-users, hasi...@gmail.com
You can but you have to do some manual work. Not sure if you are looking for out of box solution. 

epitka

unread,
Aug 31, 2016, 2:46:54 PM8/31/16
to AutoMapper-users, hasi...@gmail.com
Here is the test that works with this map. You probably could setup a DataTableToList converter and with little reflection be able to convert any table. But here is manual way...

CreateMap<System.Data.DataRow, MyDummyType>()

.ForMember(m => m.Number, s => s.MapFrom(r =>(int) r.ItemArray[0]))

.ForMember(m => m.Name, s => s.MapFrom(r => r.ItemArray[1].ToString()));




public class MyDummyType


{


public int Number { get; set; }


public string Name { get; set; }


}


[Test]

public void DataTable_to_ListOfCustomObjects_Mapping()

{

var dt = new System.Data.DataTable();

dt.Columns.Add("Number",typeof(Int32));

dt.Columns.Add("Name", typeof(string));

dt.LoadDataRow(new object[] {1, "test1"},LoadOption.OverwriteChanges);

dt.LoadDataRow(new object[] {2, "test2"},LoadOption.OverwriteChanges);

var rows = new List<DataRow>();

var enumerator = dt.Rows.GetEnumerator();

DataRow row = null;

while (enumerator.MoveNext())

{

rows.Add(enumerator.Current as DataRow);

}

var list = _mapper.Map<IEnumerable<DataRow>, IEnumerable<MyDummyType>>(rows);

 

Assert.That(list.Count(), Is.EqualTo(2));

}






      






On Tuesday, August 30, 2016 at 9:16:38 PM UTC-5, hasi...@gmail.com wrote:

Michael Powell

unread,
Aug 31, 2016, 6:43:35 PM8/31/16
to AutoMapper-users, hasi...@gmail.com
I imagine that as long as you can identify an enumeration of filtered or unfiltered rows or some such you should be able to run a mapper across that range.

I do a similar thing but on an System.Web.HttpRequestBase data. Okay, not quite the same thing, but the mapper doesn't care what the source is, per se, as long as you can identify the thing you want to map.

HTH
Reply all
Reply to author
Forward
0 new messages