LINQ:将lambda前pression作为参数来执行,并在方法返回 [英] LINQ: Passing lambda expression as parameter to be executed and returned by method

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

问题描述

因此​​,这里的情景:我有一系列的每个人都可以使用一个孤立的数据上下文或共享上下文不同的存储类。在一个孤立的情况下被使用我想添加基类,让我指定的lambda作为参数的方法的情况下,有前pression由所选择的存储库中的孤立的上下文中执行,返回一个IQueryable的结果。如何将方法签名的外观,以及如何将通过前pression上下文?

我需要的解决方案的任何可能的模式的对象/表可以用来尽可能通用

下面基本上是我所希望做的:

  IAssetRepository回购=新AssetRepository(真); // true表示孤立的背景
VAR的结果= repo.ExecuteInContext<&SOMETYPE GT;(SomeTable.Where(X =>
                                              x.SomeProp.Equals(someValue中)));


解决方案

事情是这样的:

 公开的IEnumerable< T> ExecuteInContext< T>(
  防爆pression<&Func键LT; T,BOOL>> predicate)
{
  ... //做你的东西
  //例如
  表< T> T =&的GetTable LT; T>();
  返回t.Where(predicate);
}

 公开的IEnumerable< T> ExecuteInContext< T>(
   IQueryable的< T> SRC,防爆pression<&Func键LT; T,BOOL>> predicate)
{
  返回src.Where(predicate);
}

用法:

 变种R = repo.ExecuteInContext<&SOMETYPE GT;(
          X => x.SomeProp.Equals(someValue中));

 变种R = repo.ExecuteInContext(&的GetTable LT; T>()
          X => x.SomeProp.Equals(someValue中));

假设:


  1. 表可在T来源,否则你将需要通过源了。

  2. 您知道如何根据需要修改predicate前pression。

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)));

解决方案

Something like this:

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

or

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

Usage:

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

or

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

Assumptions:

  1. Table can be derived from T, else you will need to pass the source too.
  2. You know how to modify the predicate expression if needed.

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

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