创建可重用的Linq查询

3

我有一个查询语句,它会被不同的where过滤器反复使用:

var query = from row in context.Table select row;

如何将此保存到静态类变量中,以便在不同的方法中重复使用?例如:

var results1 = query.Where(condition1);
...
var results2 = query.Where(condition2);

我不明白。你想要的东西和你已经拥有的有什么不同? - Gabe
6个回答

5

你正在正确的道路上。

考虑创建一个新方法而不是一个变量:

public IQueryable<Cust> ListActiveCustomers()
{
     return dataContext.Customers.Where(c=>c.IsActive==true);
}

你可以在该方法可见的任何地方使用它:
 //Active Customers with no invoices due.
 var activePaidCustomers = ListActiveCustomers().Where(c=>c.InvoicesDue==0)
                                                .OrderByDescending(c=>c.LastPaidOn)
                                                .ToList();

1
由于我没有全局 ObjectContext,所以我创建了一个参数化的 List() 方法:private IQueryable<Cust> List(MyContext ctx){ return ctx.Customers...}。 - dstr

3

像这样:

Expression<Func<TypeYoureQueryingAgainst, bool>> query = p => p.Value == someValue; // etc..

接下来你可以按照以下步骤操作,其中TypeYoureQueryingAgainst是指存储库或者其他你所使用的模式:

repository.Where(query);

希望您能理解。

有点意思……但是我该如何向它发送参数呢?我已经创建了这个:Expression<Func<MyTable, int, bool>> query = (table, id) => table.Id == id;。我可以使用它作为context.MyTable.Where(query),但我该如何向“query”发送id参数呢? - dstr

2
这段代码:
var query = from row in context.Table select row;

功能上等同于:

var query = context.Table;

所以你不需要保留这个query变量以便重复使用,直接使用context.Table即可:

var results1 = context.Table.Where(condition1);
...
var results2 = context.Table.Where(condition2);

1

只需将var替换为IEnumerable<RowType>(或IQueryable<RowType>),其中RowType是结果序列中每个项目的(非匿名)类型:

static IEnumerable<RowType> query = from ... select row; // row is of RowType.

1

首先,找出query的确切类型是第一步。最简单的方法是在调试器中逐步执行使用它的代码,并查看它所说的类型是什么(可能是IQueryable<RowType>IOrderedQueryable<RowType>)。


0

如果您的where筛选器是简单标量,则另一种选择是在数据库上下文的DbSet属性上创建扩展方法。

如果您的DbContext如下:

public class MyContext : DbContext
{
    ...
    public DbSet<Customer> Customers { get;set; }
    ...
}

您可以在 CustomersDbSet 上创建可重用的查询,例如:
public static class MyDbContextExtension
{
   public static IEnumerable<Customer> GetByName(this DbSet<Customer> customers, string name)
   {
       return customers.Where(c => c.Name.Contains(name));
   }
}

然后像这样使用它:

var context = new MyContext();
var jedis = context.Customers.GetByName("skywalker");
if(jedis.Any())
{
    logger.Log("These aren't the customers you're looking for");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接