2

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?

3 Answers 3

3

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>();

Sign up to request clarification or add additional context in comments.

Comments

2

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();

2 Comments

Do you have a link for how to use reflections?
@Lahib how do you survive without knowing the .NET documentation? As Reflection is a core part of the .NET framework - guess what, it is in the documentation.
0

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 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.