Евгений Евгений - 25 days ago 6
C# Question

call method with params in arguments through reflection c#

Method return record from Database.

public T Find(params object[] primaryKeys)
{
var dbSet = _sessionContext.Set<T>() as DbSet<T>;

return dbSet != null ? dbSet.Find(primaryKeys) : null;
}


I'm trying to call in through reflection

var methodCreateReadRepositoryEntity =
typeof(IRepositoryFactory)
.GetMethod("CreateReadRepository")
.MakeGenericMethod(entityMetadata.GetEntityType());

var entityReadRepository =
methodCreateReadRepositoryEntity
.Invoke(_repositoryFactory, new object[] { _sessionMarketContext });

List<object> keys = new List<object>();

keys.Add(value);

var methodEntityGet =
entityReadRepository.GetType().GetMethod("Find", new Type[] { typeof(object[])});

var fromRepo =
methodEntityGet.Invoke(entityReadRepository, new object[]{new []{ keys.ToArray()[0]}});


value is Guid. And I have error


The type of one of the primary key values did not match the type defined in the entity.
Exception has been thrown by the target of an invocation.

Answer

Your last line should be as follows. You need to be explicit with the array type, and there is no need to create a List.

var fromRepo = 
    methodEntityGet.Invoke(entityReadRepository, new object[]{new object []{value}});