Reputation: 1365
I am creating a Web service that takes to input parameters and returns data in objects. I have created a class Sending which has many properties.
I am retrieving the data from a database and loading them into a datatable. I am using datatables because i there can be many rows and i need to create an object of the sending class for each row.
I have also created get and set properties for each variable in the sending class.
Is there any way to insert the data from the datatable into the class objects?
Upvotes: 2
Views: 2494
Reputation: 64
Try this sample Extension. improve it with your requirement.
public static IEnumerable<T> ToIEnumerable<T>(this DataTable dt)
{
List<T> list = Activator.CreateInstance<List<T>>();
T instance = Activator.CreateInstance<T>();
var prop = instance.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
foreach (DataRow dr in dt.Rows)
{
T ins = Activator.CreateInstance<T>();
foreach (var p in prop)
{
try
{
p.SetValue(ins, dr[p.Name], null);
}
catch { }
}
list.Add(ins);
}
return list;
}
usage:
yourDataTable.ToIEnumerable<YourClassModel>();
Upvotes: 3
Reputation: 131748
Don't try to do this by hand. ORMs do exactly this job in a much easier way. You can actually use a Micro-ORM like Dapper.NET or Massive to load data from the database as objects with a minimum of configuration.
For example, this query Dapper.NET query will load all Dog objects with the specified age:
public class Dog
{
public int? Age { get; set; }
...
}
var dogs = connection.Query<Dog>("select Age = @Age", new { Age = 5 });
Upvotes: 0
Reputation: 32729
If you have already created matching datamodel, then you can do something like this
IList<YourClass> items = yourdatatable.AsEnumerable().Select(x =>
new YourClass
{
field1 = x.Field<int>("idcolumnName"),
field2 = x.Field<string>("otherColumn")
}).ToList();
Upvotes: 2