开发者

Creating reusable Linq queries

I have a select query which is used over and over with different where filters:

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

How can I save this into a static class variable so I can reuse it in different methods? Like:

var results1 = query.Where(condition1);
...
var results2 = query.Where(condition2);开发者_JAVA技巧


You're on the right track.

Consider creating a new method instead of a variable:

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

You can then consume this from anywhere that method is visible:

 //Active Customers with no invoices due.
 var activePaidCustomers = ListActiveCustomers().Where(c=>c.InvoicesDue==0)
                                                .OrderByDescending(c=>c.LastPaidOn)
                                                .ToList();


Something like this:

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

Then you could do the following, where TypeYoureQueryingAgainst is in the repository or whatever pattern you're using:

repository.Where(query);

Hope that makes sense..


This code:

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

Is functionally equivalent to:

var query = context.Table;

So you don't need to keep this query variable to reuse it, just use context.Table directly:

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


Simply replace var with IEnumerable<RowType> (or IQueryable<RowType>) where RowType is the (non-anonymous) type of each item in the result sequence:

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


Well, the first step is finding out the exact type of query. The easiest way is to step through so code using it in the debugger, and see what it says the type is (probably IQueryable<RowType> or IOrderedQueryable<RowType>)


Another alternative if your where filters are simple scalars is to create extension method(s) on the DbSet properties of your database context.

If your DbContext is like:

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

You can create reusable queries on the Customers DbSet like:

public static class MyDbContextExtension
{
   public static IEnumerable<Customer> GetByName(this DbSet<Customer> customers, string name)
   {
       return customers.Where(c => c.Name.Contains(name));
   }
}

And then use it like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜