vendredi 12 février 2021

"Object does not match target" while trying to invoke method using Reflection [duplicate]

I am solving a problem where I need to iterate over bunch of DbSets and insert into them some data stored in Lists. I have decided that Reflection might be the best way, because otherwise there would be a lot of repetive code.

Type propType = _databaseContext.GetType().GetProperty(contextProp.Name)?.PropertyType;
MethodInfo methodInfo = propType.GetMethod("AddRange", new Type[] {values.GetType()});
methodInfo.Invoke(_databaseContext, new[] {values});

This peace of code throws exception which stays:

Object does not match target type.

I am using new Type[] {values.getType()} as a second parameter of GetMethod because otherwise it throwed exception saying Ambiguos match found.. I think it should assure that AddRange method accepts Lists as a parameters, but it doesn't.

Does anyone know where the problem might be?





Aucun commentaire:

Enregistrer un commentaire