简体   繁体   中英

How to pass Expression<Func<T, bool>> predicate as a parameter to a method?

I have a higher order function for handling transaction:

public static void ExecuteTransaction<Context, FunctionParameter>(Action<FunctionParameter> functionToBeExecuted,
                                                                           FunctionParameter parameter,
                                                                           Context context)
                                                                           where Context : DbContext
        {
            using (var transaction = context.Database.BeginTransaction())
            {
                try
                {
                    functionToBeExecuted(parameter);
                    context.SaveChanges();

                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

How can i change the ExecuteTransaction method to accept this method and its parameter?:

public void DeleteBy(Expression<Func<TEntity, bool>> predicate)
{
    var results = DbSet.Where(predicate).ToList();
    DbSet.RemoveRange(results);
}

If I understood correctly, you are trying to pass DeleteBy to ExecuteTransaction , and let ExecuteTransaction run the method.

Assuming you have a Expression<Func<TEntity, bool>> to act as the parameter of DeleteBy prepared already:

Expression<Func<TEntity, bool>> param = entity => /*some lambda that returns a bool */;

you can pass DeleteBy directly, without any changes to ExecuteTransaction , because DeleteBy matches the signature of Action<T> :

ExecuteTransaction(DeleteBy, param, context);

The compiler will automatically infer that FunctionParameter is Expression<Func<TEntity, bool>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM