开发者

Recursive call to generic function with DataRow parameter - MakeGenericMethod Fails

开发者 https://www.devze.com 2023-03-21 03:22 出处:网络
the question is: if i have MyConvertDataRowToEntity(DataRow row ) and I call in with T object from type Parent and inside I call the same function with desendant type Child how should I pass the Data

the question is : if i have MyConvertDataRowToEntity(DataRow row ) and I call in with T object from type Parent and inside I call the same function with desendant type Child how should I pass the DataRow parameter ? The problem is created when Invoke of MakeGenericMethod called. Did change the type to DataSet , string and String types . No luck. (I recognize the children object bu prefix in column names - PrefixDataColumn )

public static T MyConvertDataRowToEntity<T>(DataRow row ) where T : class, new()
    {

        Type objType = typeof(T);
        Type parentObjType = typeof(T);
        T obj = Activator.CreateInstance<T>(); //hence the new() contsraint
        PropertyInfo propertyGenericType = null;
        object childInstance = null;
        PropertyInfo property;
        string childColumnName = string.Empty ;
        foreach (DataColumn column in row.Table.Columns)
        {
            column.ColumnName = column.ColumnName.Replace("_", "");

            string PrefixDataColumn;
            if (column.ColumnName.IndexOf(".") > (-1))
            {
                ///gets the prefix that is the same as child entity name
                PrefixDataColumn = column.ColumnName.Substring(0, column.ColumnName.IndexOf("."));
                ///the column name in the child
                int length = column.ColumnName.Length - 1;
                int start = column.ColumnName.IndexOf(".") + 1;
                childColumnName = column.ColumnName.Substring(column.ColumnName.IndexOf(".") + 1);
                propertyGenericType = objType.GetProperty(PrefixDataColumn,
                                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
                parentObjType = objType;
                if (propertyGenericType != null)
                {
                    Type childType = propertyGenericType.PropertyType;
                    objType = childType;
                    childInstance = Activator.CreateInstance(propertyGenericType.PropertyType);


                    // get the get method for the property
                    MethodInfo method = propertyGenericType.GetGetMethod(true);
                    // get the generic get-method generator 
                    MethodInfo genericHelper = typeof(DataUtil).GetMethod("MyConvertDataRowToEntity", BindingFlags.Public | BindingFlags.Static);

                    List<Type> signature = new List<Type>();
                    // first type parameter is type of target object
                    signature.Add(childType);

                    //next parameters are real types of method arguments
                    foreach (ParameterInfo pi in genericHelper.GetParameters())
                    {
                        signature.Add(pi.ParameterType);
                    }

                    // last parameters are known types of method arguments
                    signature.AddRange(typeof(T).GetGenericArguments());

                    // reflection call to the generic get-method generator to generate the type arguments
                    //MethodIn开发者_高级运维fo constructedHelper = genericHelper.MakeGenericMethod(signature.ToArray());

                    // reflection call to the generic get-method generator to generate the type arguments
                    MethodInfo constructedHelper = genericHelper.MakeGenericMethod(childType );

                    // now call it. The null argument is because it's a static method.
                    object ret = constructedHelper.Invoke(null, new object[] { method });

                   // object myObj =  method.Invoke(null, row);
                   //// property.SetValue(obj, MyConvertDataRowToEntity<childInstance>(DataRow row),null);
                   // childInstance = DataUtil.GetMethod("MyConvertDataRowToEntity").MakeGenericMethod(childType); //MyConvertDataRowToEntity<object>(row); 

                    //childType initializedChild = ;
                    //property.SetValue(obj, value, null);
                    //objType = parentObjType;
                }
                else
                {
                    continue; 
                }
            }


        }
        return obj;
    }

Getting this error : Object of type 'System.Reflection.RuntimeMethodInfo' cannot be converted to type 'System.Data.DataRow'.

Is there any solution for this ?

p.s. Narrowed down the code as much as i could.

How can I invoke the Method recursivly with desedant types and pass datarow ?


The reason for the error is because you are calling MyConvertDataRowToEntity<ChildType> but then passing in the getaccessor methodinfo for the property as the parameter instead of a data row containing only those fields.

If you want to continue with the code processing logic you are currently using you would need to construct a new datarow containing the fields you wanted (with the prefix and ".") removed from the start of the column names.

Alternatively you could create a helper method the accepted a column name, the source object and it simply updated the value.

static void UpdateItemProperty<T>(T item, string columnName, object rowValue) {
  var prefixColumn=columnName.IndexOf(".")==-1 ? columnName : columnName.Split(".")[0];
  var pi = typeof(T).GetProperty(prefixColumn // Add your binding flags);
  // if pi==null then there is an error...
  if (column.ColumnName.IndexOf(".") == (-1)) { // No Nesting
    pi.SetValue(item,rowValue);
    return;
  }
  // Nesting 
  var child=pi.GetValue(item);
  if (child==null) {
        // Logic here to get childs type and create an instance then call pi.SetValue with child
  }
  var remainder=string.Join(',',columnName.Split(".").Skip(1).ToArray());
  // make your generic method info for UpdateItemProperty with pi.PropertyType into mi
  mi.Invoke(null,new object[] { child,remainder,value };
}
0

精彩评论

暂无评论...
验证码 换一张
取 消