Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate class from DataTable

I have a class that I need to hydrate from a DataTable object. Usually I do this the manual way. (see code snipit). The DataTable object populated using ADO.NET and TSql. I need to transfer the values from the DataTable into my .NET class. Is there a utility method that will do this for me automagically? So that I can avoid repetitive code like the following?

            DriverSummary driver = new DriverSummary();
            driver.Id = (int)row["Id"];
            driver.UserId = row["UserId"] as string;
            driver.Name = row["Name"] as string;
            driver.TruckType = row["TruckType"] as string;
            summaries.Add(driver);

I know that the Entity Framework is a tool that is supposed to fill this gap. I haven't quite made the jump to Entity Framework. For now I'd like to have a method that is similar to MVC's utility method UpdateModel() Which is lightweight and simple and hydrates a class from a list of form-value pairs by matching up key names with property names.

Such a utility method would save me tons of time!

like image 405
BrokeMyLegBiking Avatar asked Oct 11 '22 09:10

BrokeMyLegBiking


People also ask

How to create a DataTable and add rows to it in c#?

After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method.


1 Answers

Like mentioned above I believe AutoMapper can do this now. You could also look at a ValueInjecter. ValueInjecter and DataTable

like image 200
Derek Beattie Avatar answered Oct 14 '22 19:10

Derek Beattie