LINQ:将 lambda 表达式作为要执行的参数并由方法返回 [英] LINQ: Passing lambda expression as parameter to be executed and returned by method

查看:34
本文介绍了LINQ:将 lambda 表达式作为要执行的参数并由方法返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里是场景:我有一系列不同的存储库类,每个类都可以使用独立的数据上下文或共享上下文.在使用隔离上下文的情况下,我想向基类添加一个方法,该方法允许我将 lambda 指定为参数,让该表达式由所选存储库的隔离上下文执行并返回 IQueryable 结果.方法签名看起来如何,以及如何将表达式传递给上下文?

So here is the scenario: i have a series of different repository classes that each can use an isolated data context, or a shared context. In the cases where an isolated context is being used i want to add a method to the base class that will allow me to specify the lambda as the parameter, have that expression be executed by the isolated context of the chosen repository and return an IQueryable result. How would the method signature look, and how to a pass the expression to the context?

我需要解决方案尽可能通用,因为可以使用任何可能的模型对象/表.

I need the solution to be as generic as possible as any possible model object/table could be used.

这基本上是我想要做的:

Here is basically what i am looking to do:

IAssetRepository repo = new AssetRepository(true); // true indicates isolated context
var results = repo.ExecuteInContext<SomeType>(SomeTable.Where(x => 
                                              x.SomeProp.Equals(SomeValue)));

推荐答案

是这样的:

public IEnumerable<T> ExecuteInContext<T>(
  Expression<Func<T,bool>> predicate)
{
  ... // do your stuff
  //eg
  Table<T> t = GetTable<T>();
  return t.Where(predicate);
}

public IEnumerable<T> ExecuteInContext<T>(
   IQueryable<T> src, Expression<Func<T,bool>> predicate)
{
  return src.Where(predicate);
}

用法:

var r = repo.ExecuteInContext<SomeType>( 
          x => x.SomeProp.Equals(Somevalue));

var r = repo.ExecuteInContext(GetTable<T>(), 
          x => x.SomeProp.Equals(Somevalue));

假设:

  1. 表可以从 T 派生,否则您也需要传递源.
  2. 如果需要,您知道如何修改谓词表达式.

这篇关于LINQ:将 lambda 表达式作为要执行的参数并由方法返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆