Rossana Rossana - 1 year ago 116
C# Question

binding datatable columns into class model

I have a

and a
. 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
with the following data column,

ModelID | ModelName

The records f the
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 (DataRow row in MyDataTable)
MyModel model = new MyModel()
model.ModelID = Convert.ToInt32(row["Position"].ToString());
model.ModelName = row["ModelName"].ToString();

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 Source

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, 

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download