Question

In my project i have a fill method.

  public IList<MyModel> Fill(DataTable dt)
    {
        IList<MyModel> IProperty = new List<MyModel>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            MyModel Property = new MyModel
            {
                Name= dt.Rows[i]["Name"].ToString(),
                Surname = dt.Rows[i]["Surname"].ToString(),
                Age = dt.Rows[i]["Age"].ToString(),
            };
            IProperty.Add(Property);
        }
        return IProperty;
    }

It fill my model from datatable. But i must write this fill method for all model. I dont want to write this method all the time. I need a solution for this. I'm open to any kind of proposal

Not:I dont want to use Entity framework or other ORM frameworks.

Was it helpful?

Solution

If you can make sure the field names and properties of the object with the same name, try this:

public IEnumerable<T> Fill<T>(DataTable dt)
    where T : new()
{
    return dt.AsEnumerable().Select(row =>
    {
        var obj = new T();
        var properties = 
            from p in obj.GetType().GetProperties()
            join c in dt.Columns.Cast<DataColumn>() on p.Name equals c.ColumnName
            select new {p, c};
        foreach (var item in properties)
            item.p.SetValue(obj, row[item.c]);
        return obj;
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top