Rossana Rossana - 3 months ago 21
C# Question

binding datatable columns into class model

I have a

DataTable
and a
Model
. Are there any other ways on how to map the columns on the members of the class? Let me illustrate my current way,

class Model

private class MyModel
{
public int ModelID { get; set; }
public string ModelName { get; set; }
}


and a
DataTable
with the following data column,

ModelID | ModelName


The records f the
Datatable
is from teh result of my sql query.

SELECT ModelID, ModelName FROM tableName


Now, when I map the records to
IList<MyModel> myList
, I do a
foreach
loop.

foreach (DataRow row in MyDataTable)
{
MyModel model = new MyModel()
model.ModelID = Convert.ToInt32(row["Position"].ToString());
model.ModelName = row["ModelName"].ToString();
myList.Add(model);
}


and this totally works fine. This is not really a problem but it is very time consuming considering that i have many data tables and has 20 columns or more, and many more classes.

What I am looking for is if there are other ways to do it. Like an existing class but I really don't know what's its name.

If this question has already been asked, please help me find the link.

Thank you.

Answer

AutoMapper should be able to do this, though you'll want to test how efficient it is. This post seems to have some success with it:

public class Person
{
    public string First_Name { get; set; }
    public string Last_Name { get; set; }
    public string User_Name { get; set; }
}

List<Person> people = AutoMapper.Mapper.DynamicMap<IDataReader, 
                      List<Person>>(sourceDataTable.CreateDataReader());

Note that under the hood it's probably doing something very comparable to what you're already doing, but mixing in some reflection to make it more generic. What you're doing isn't terribly inefficient per se, unless you're talking about really high volume and need to squeeze out every ounce of performance possible.

Replacing the DataTable entirely with an ORM may also work for you. Entity Framework is a pretty common standard, though there are many others. (Dapper is known for its fast performance, if that's what you're looking for.)

If the "time consuming" part isn't the runtime performance but rather the development time, I wouldn't worry a whole lot about it. If you can spend some time abstracting the DataTables behind a translation layer into POCO objects, the benefits will likely pay off in the long run. It's a lot of menial code, but it's a one-time expense.

Comments