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
}