Reputation: 90
Hy, this is my first question here! I'm really struggling with these code bellow:
I have these class:
public class Home {
public List<Parameter> Parameter { get; set; }
}
I also have a function with this specs:
public static List<T> DataTableMapToList<T>(DataTable dtb)
{ ... }
In another class when I need call these function, I need pass the type of the my class but I'm in a reflection properties loop:
public void Initialize(ref object retObject)
{
using (var db = this)
{
db.Database.Initialize(force: false);
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = sStoredProcedure;
try
{
// Run the sproc
db.Database.Connection.Open();
DbDataReader reader = cmd.ExecuteReader();
DataSet ds = new DataSet();
ds.EnforceConstraints = false;
ds.Load(reader, LoadOption.OverwriteChanges, sTables);
var propertys = GetGenericListProperties(retObject);
foreach (DataTable table in ds.Tables) {
foreach (var info in propertys)
{
if (info.Name == table.TableName)
{
Type myObjectType = info.PropertyType;
// Create an instance of the list
var list = Activator.CreateInstance(myObjectType);
var list2 = DataTableMapToList<???>(table).ToList();
//Where the variable myObjectType is the TYPE of the class where I need to pass on the ??? marker
info.SetValue(retObject, list, null);
}
}
}
}
finally
{
db.Database.Connection.Close();
}
}
}
Where: retObject -> An instance of Home; info -> It's Home.Parametro property;
I wanna set - by reflection - the property dynamically. Everything is working without the call of the function with generic type. But I need call the function to populate the property correctly.
I've tried everything:
Pass as object and try convert after (I got an error of IConverter must be implemented);
Tried to put all my code - just for test - of the DataTableMapToList() and even so I got error of object conversion;
Force send list for my final variable but I have converter error again.;
I don´t know if I was clear enough about what I really need but I'm spend about 4 hours looking for a solution until know.
Upvotes: 0
Views: 150
Reputation: 6882
Given that there is a class with a static generic function:
public static class Utils
{
public static List<T> DataTableMapToList<T>(DataTable dtb)
{ ... }
}
It can be invoked using reflection:
IEnumerable InvokeDataTableMap(DataTable dtb, Type elementType)
{
var definition = typeof(Utils).GetMethod("DataTableMapToList");
var method = definition.MakeGenericMethod(elementType);
(IEnumerable) return method.Invoke(null, new object[]{dtb});
}
Upvotes: 1