mercredi 24 octobre 2018

Calling a Generic Method with Lambda Expressions parameter (and a Type only known at runtime)

I have a Repository:

public interface IRepository<TEntity> : ICommandRepository<TEntity>, IBaseRepository, IDisposable, IQueryableRepository<TEntity>
{
}
public interface ICommandRepository<TEntity> : IBaseRepository, IDisposable
{
    void Delete(Expression<Func<TEntity, bool>> predicate);     
}

My Goal is to invoke Delete method with Lamda Expresion Params, if I know the Type of "TEntity" in runtime. Example, how I call this method:

public JsonResult DeleteRows(int[] ids)
{
    var repo = DependencyResolver.Current.GetService<IRepository<WORKINGHOURS>>();
    repo.Delete(e => ids.Contains(e.Id));
    repo.UnitOfWork.Commit();
}

Now, I want to invoke same method using reflection and Type on runtime:

public JsonResult DeleteRows(string type, int[] ids)
{
    Type dbObjectType = Type.GetType(type);
    Type repositoryType = typeof (IRepository<>).MakeGenericType(dbObjectType);
    var repositoryInstance = ServiceLocator.CurrentLifetimeScope.Resolve(repositoryType);

    MethodInfo deleteMethod = repositoryType.GetMethod("Delete");
    // TODO:
    // Expression<Func<WORKINGHOURS, bool>> searchQuery = p => ids.Contains(p.Id);
    var delete = deleteMethod.Invoke(repositoryInstance, .....);
    // Commit
}

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire