英文:
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);
}
英文:
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);
}
答案1
得分: 2
如果我理解正确,您试图将DeleteBy传递给ExecuteTransaction,并让ExecuteTransaction运行该方法。
假设您已经准备好一个Expression<Func<TEntity, bool>>来作为DeleteBy的参数:
Expression<Func<TEntity, bool>> param = entity => /*一些返回bool的lambda表达式*/;
您可以直接传递DeleteBy,无需对ExecuteTransaction进行任何更改,因为DeleteBy与Action<T>的签名匹配:
ExecuteTransaction(DeleteBy, param, context);
编译器将自动推断FunctionParameter为Expression<Func<TEntity, bool>>。
英文:
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>>.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论