1

I have created a instance of an entity model called MyModel but I need to use this instance as a type in my helper class so that I can convert a datatable to whatever model that was dynamically created. Everything works if I explicitly pass the actual model to the helper class for example:

var data = Helper.DataTableToList<MyActualEntity>(datatable);

but I need to do this dynamically. This is my helper class

 public static class Helper
    {
        /// <summary>
        /// Converts a DataTable to a list with generic objects
        /// </summary>
        /// <typeparam name="T">Generic object</typeparam>
        /// <param name="table">DataTable</param>
        /// <returns>List with generic objects</returns>
        public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
        {
            try
            {
                List<T> list = new List<T>();

                foreach (var row in table.AsEnumerable())
                {
                    T obj = new T();

                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        try
                        {
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                            propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    list.Add(obj);
                }

                return list;
            }
            catch
            {
                return null;
            }
        }
    }

This is me creating the entity dynamically by tablename. It works fine until I need to pass they type to the Helper Class and I get the error "MyModel is a variable but is used like a type"

var assembly = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x => x.FullName.Contains("MyNameSpace.Model")).FirstOrDefault();
var type = assembly.GetTypes()
    .FirstOrDefault(t => t.Name == tableName);

if (type != null)
{
    System.Data.Entity.DbSet myDbSet = ctx.Set(type);                       
   var MyModel = myDbSet.Create(); <--Entity is created

    var data = Helper.DataTableToList<MyModel>(dt);  <--Errors here                           
}
dbc
  • 104,963
  • 20
  • 228
  • 340
Terrance Jackson
  • 606
  • 3
  • 13
  • 40
  • If you have your `Type type`, you can invoke your `Helper.DataTableToList` method by using the mechanism from [Invoking static methods containing Generic Parameters using Reflection](https://stackoverflow.com/q/3052372/3744182) and [How do I use reflection to call a generic method?](https://stackoverflow.com/q/232535/3744182). In fact this may be a duplicate, agree? – dbc Dec 14 '18 at 03:36

2 Answers2

1
System.Reflection.MethodInfo MI = typeof(Helper).GetMethod("DataTableToList");   
System.Reflection.MethodInfo generic = MI.MakeGenericMethod(MyModel.GetType());    
var data = generic.Invoke(null, new object[] { //YourDataTableHere });

You have to use reflection as @dbc stated above. Then you have to invoke the generic method and cast a new object as your datatable. If you are not using static methods then reverse the arguments

CodeMan03
  • 570
  • 3
  • 18
  • 43
0

AS per your description, Helper method is extension method on DataTable so you should use below line of code:

var data = dt.DataTableToList<MyModel>();

you can use same code for any type of model as it is generic method. Example code I executed at my end. Helper Class Extension:

public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
        {
            try
            {
                List<T> list = new List<T>();

                foreach (DataRow row in table.Rows)
                {
                    T obj = new T();
//change made at this line
                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        try
                        {
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                            propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    list.Add(obj);
                }

                return list;
            }
            catch
            {
                return null;
            }
        }

Model Class:

 public class Data
        {
            public string Client_Description { get; set; }
            public string Client_Code { get; set; }
            public string Brand_Description { get; set; }
            public string Brand_Code { get; set; }
        }

Calling method:

DataTable inputData = null; // Get the DataTable

Call extension method:

var dataList = inputData.DataTableToList<Helper.Data>();

Or

var data = Helper.DataTableToList<Helper.Data>(inputData);

Please share your source code with me if you still face issue.

enter image description here

Ashish Mishra
  • 667
  • 7
  • 14