Reusing Base Linq Query from one method to another

linq to sql parameterized query
linq to sql execute sql command
c sql query using linq
linq raw sql
linqpad execute sql command
linq query sql server
linq sql query
how to execute sql query in visual studio 2015

I am trying to remove duplicate code throughout my project and I am at a standstill trying to figure this out. What I am trying to do is create a base linq query that will be reused to add things like Where, Take...etc in multiple different methods.

public IQueryable<Object> FooLinq(int id)
{
    using (var ctx = new dbEntities())
    {
        var results =
            (from account in ctx.account
                join memberProducts in ctx.tblMemberProducts on account.Id equals memberProducts.AccountId                 
                orderby account.date descending
                select new{account,memberProducts}).ToList();
        return results;
    }
}

So that would be by base query above and I would have a seperate method that would reuse VioLinq but this time would use a where clause in it.

public List<IncomingViolations> Foo1(int id)
{
    //Linq query FooLinq() where Name == "Bob"
}

You'll need to do two things:

  1. Return the query prior to materializing it.
  2. Make sure the context is still in scope when the final query is materialized.

These two requirements will play off each other somewhat, and there are a number of approaches you can take to meet them.

For example, you could make your method take the context as a parameter, forcing the caller to provide it and manage its lifecycle.

public IQueryable<AccountInfo> FooLinq(DbEntities ctx, int id)
{
        return
                from account in ctx.account                        
                orderby account.date descending
                select new AccountInfo()
                {
                    Name = account.Name,
                    Mid = account.MemberID,
                    Date = account.Date,
                    Address = account.Address,

                };
}

public List<IncomingViolations> Foo1(int id)
{
    using(var ctx = new dbEntities())
    {
        //Linq query FooLinq() where Name == "Bob"
        return FooLinq(ctx).Where(v => v.Name == "Bob").ToList();
    }
}

You could alternatively inject the context as a constructor-injected dependency, and use a DI framework to manage the context's lifecycle.

How to: Store and Reuse Queries, LINQ to SQL supports the use of compiled queries for this purpose. Other approaches are possible. For example, compiled queries can be stored as static members on a partial class Compile(Function(db As Northwnd, _ id As String) _ db. CompiledQuery · Query Concepts · Querying the Database  It allows to create query snippets and use them everywhere you in a linq query. Following the example of Hamid, create the following expression: System.Linq.Expressions.Expression<Func<Foo, bool>> selector = x => x.Contains(""); You can now use this query everywhere in your linq queries like this: query.AsComposable().Where(o => selector.Pass(o));


You can do it as Queryable then add conditions to it. For example:

public List<account> GetAccountsByName(string name, bool usePaging, int offset = 0, int take = 0) {
   var query = GetMyQuery();
   query = query.Where(x => x.Name == name);
   query = query.OrderBy(x => x.Name);
   if(usePaging) {
      query = query.Take(take).Skip(offset);
   }
   query = PrepareSelectForAccount(query);
   return query.ToList();    .
}

public IQueryable<account> GetMyQuery(){
 return ctx.account.AsQueryable();
}
public IQueryable<account> PrepareSelectForAccount(IQueryAble<account> query){
     return query.Select(select new AccountInfo()
                {
                    Name = account.Name,
                    Mid = account.MemberID,
                    Date = account.Date,
                    Address = account.Address,

                }
      );
}

Merging Expression Trees to Reuse in Linq Queries, A helper method contains the Select() call to map Car entities to the basic DTO. Now the Merge extension method can be used to merge an  There are two flavors of LINQ – query and methods chaining. If you are versed in the query syntax, consider the fact method chaining lend itself to expressions reuse while query syntax doesn't. Actually, using tools like the ones described here you might get it to work in query syntax but it would make you queries much less readable, losing


Sure, but don't call .ToList(), and return IQueryable<T> instead of List<T>. LINQ is based on the concept of deferred execution which means the query is not actually performed until the enumerable is iterated over. Until then, all you have done is built an object which knows how to do the query when the time comes.

By returning an IQueryable<T> from a function that sets up the "basic query," you are then free to tack on additional LINQ methods (such as .Where() or .Take()) to produce a modified query. At this point you are still simply setting up the query; it is actually performed only when you iterate over the enumerable, or call something like .ToList() which does that for you.

LINQ, With the merging helper method we can reuse the query for the basic list and just A helper method contains the Select() call to map Car entities to the basic DTO. I've already written another post named Always Check Generated SQL back  c# - method - linq query examples Reusing LINQ query results in another LINQ query without re-querying the database (6) I have a situation where my application constructs a dynamic LINQ query using PredicateBuilder based on user-specified filter criteria ( aside: check out this link for the best EF PredicateBuilder implementation ).


Beginning VB 2008: From Novice to Professional, The copied and pasted code reuses classes and functionality from another problem context. I find this happens a lot in my projects. So how In fact, LINQ can always be avoided by using Visual Basic code. So then why use LINQ? The reason is that LINQ makes it easier for you to write complicated search queries that are  Which leads to your first option in creating subqueries in LINQ. LINQ doesn't execute your query until you "realize" it. You can realize a query by calling some method on it (ToList is a good example) or by working with individual objects in the result (by using a foreach loop to process each object in the query's result).


SQL Server Database Programming with Visual Basic.NET: Concepts, , You can use the IsMatch() method in the where clause of a LINQ query. paragraphs, pages, or any other criteria, and then perform additional splits if they are required in your Note that the query is 'reused' after it is executed the first time. Method-Based Query Syntax Examples: Join (LINQ to DataSet) 03/30/2017; 3 minutes to read +7; In this article. Joining is an important operation in queries that target data sources that have no navigable relationships to each other, such as relational database tables.


Black Art – LINQ expressions reuse, When developing a complex line of business system queries, reuse is lambda (​the Select() method call), and the other one is the parameter  It would be nice if you could query a code base in a structured way. Basic search functionality from an IDE like Visual Studio isn’t powerful enough. NDepend allows you to query .Net code using LINQ syntax through CQLinq – Code Query LINQ. In this blog post we’ll discuss how to query your code base using CQLinq. An Example