如何将 Expression<Func<T, bool>> 谓词作为参数传递给方法?
How to pass Expression<Func<T, bool>> predicate as a parameter to a method?
我有一个处理交易的高阶函数:
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;
}
}
}
如何更改 ExecuteTransaction 方法以接受此方法及其参数?:
public void DeleteBy(Expression<Func<TEntity, bool>> predicate)
{
var results = DbSet.Where(predicate).ToList();
DbSet.RemoveRange(results);
}
如果我没理解错的话,你正试图将 DeleteBy
传递给 ExecuteTransaction
,并让 ExecuteTransaction
运行 方法。
假设您已经准备好一个Expression<Func<TEntity, bool>>
作为DeleteBy
的参数:
Expression<Func<TEntity, bool>> param = entity => /*some lambda that returns a bool */;
你可以直接传递DeleteBy
,不需要对ExecuteTransaction
做任何修改,因为DeleteBy
匹配Action<T>
的签名:
ExecuteTransaction(DeleteBy, param, context);
编译器会自动推断出FunctionParameter
是Expression<Func<TEntity, bool>>
。
我有一个处理交易的高阶函数:
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;
}
}
}
如何更改 ExecuteTransaction 方法以接受此方法及其参数?:
public void DeleteBy(Expression<Func<TEntity, bool>> predicate)
{
var results = DbSet.Where(predicate).ToList();
DbSet.RemoveRange(results);
}
如果我没理解错的话,你正试图将 DeleteBy
传递给 ExecuteTransaction
,并让 ExecuteTransaction
运行 方法。
假设您已经准备好一个Expression<Func<TEntity, bool>>
作为DeleteBy
的参数:
Expression<Func<TEntity, bool>> param = entity => /*some lambda that returns a bool */;
你可以直接传递DeleteBy
,不需要对ExecuteTransaction
做任何修改,因为DeleteBy
匹配Action<T>
的签名:
ExecuteTransaction(DeleteBy, param, context);
编译器会自动推断出FunctionParameter
是Expression<Func<TEntity, bool>>
。