I am trying to write a generic method that will convert a DataTable to a list of strongly typed objects.
The code that I’m working with so far is…
public List<T> ImportTable<T>(String fileName, String table)
{
//Establish Connection to Access Database File
var mdbData = new ConnectToAccess(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS\" + fileName + ".mdb;");
var tableData = new List<T>();
foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
{
tableData.Add(ConvertRowToType<T>(row));
}
return tableData;
}
public T ConvertRowToType<T>(DataRow row)
{
//??? What is the best thing to do here ???
}
I’m not fixated on this code if anybody’s suggestions would require changes to it.
So let’s say I call this function passing in the type…
public class mdbConcern
{
public Int32 ConcernId { get; set; }
public String Concern { get; set; }
}
And the Data coming back in the DataTable looks like…
ConcernID Concern
1 Law and Ethics
2 Mail
3 Business English
... ...
What would be the best way to implement the ConvertRowToType(DataRow row) method?
Can someone show me how to use Func as one of the parameters so I can pass in some mapping information?
I think an
extension methodis the best way to go:Usage:
Update I see that you asked for a
Functhat would provide the mapping. I’m not sure exactly what you envisioned but here is a method I came up with:Usage:
Here’s a version using attributes on the type’s properties to store its mapping. I think it’s a more natural solution: