[英]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?:如何更改 ExecuteTransaction 方法以接受此方法及其参数?:
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.如果我理解正确,您正在尝试将
DeleteBy
传递给ExecuteTransaction
,并让ExecuteTransaction
运行该方法。
Assuming you have a Expression<Func<TEntity, bool>>
to act as the parameter of DeleteBy
prepared already:假设你有一个
Expression<Func<TEntity, bool>>
作为已经准备好的DeleteBy
的参数:
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>
:您可以直接传递
DeleteBy
,而无需对ExecuteTransaction
进行任何更改,因为DeleteBy
匹配Action<T>
的签名:
ExecuteTransaction(DeleteBy, param, context);
The compiler will automatically infer that FunctionParameter
is Expression<Func<TEntity, bool>>
.编译器会自动推断
FunctionParameter
是Expression<Func<TEntity, bool>>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.