How to reorganize several similar Linq-To-Sql queries?

Read before liner or closing: This almost exact duplicate of a previous previous question exists for the sole purpose of rephrasing the previous question to the Linq-To-Sql area. All of the answers in the previous question are valid for the Linq realm, but not valid in the Linq-To-SQL realm.

Suppose I have the following two Linq-To-SQL queries that I want to reorganize:

var someValue1 = 0;
var someValue2= 0;
var query1 = db.TableAs.Where( a => a.TableBs.Count() > someValue1 )
              .Take( 10 );
var query2 = db.TableAs.Where( a => a.TableBs.First().item1 == someValue2)
              .Take( 10 );

Note that only the Where parameter is changed. Is there any way to put a request inside a method and pass the Where parameter as an argument?

All the solutions published in the previous question were tried and failed at runtime when I try to list the result.

The exception was: "Unsupported congestion used for the query operator" Where "

+3
source share
2 answers

That's right. You must write:

public IQueryable<A> First10(Expression<Func<A,bool>> predicate)
{
    return db.TableAs.Where(predicate).Take(10);
}

(Assuming that TableA IQueryable<A>.)

Call the following address:

var someValue1 = 0;
var someValue2= 0;
var query1 = First10(a => a.TableBs.Count() > someValue1);
var query2 = First10(a => a.TableBs.First().item1 == someValue2);

I believe this will work ...

The difference between this and the answers to your previous question is basically what this method accepts Expression<Func<T,bool>>instead of just Func<T,bool>, so it ends up using Queryable.Whereinstead Enumerable.Where.

+6
source

, . . :

var query = 
Products
    .Where(p => p.Description.Contains(description))
    .Where(p => p.Discontinued == discontinued);

:

public static IEnumerable<Product> ByName(this IEnumerable<Product> products, string description)
{
    return products.Where(p => p.Description.Contains(description));
}


public static IEnumerable<Product> AreDiscontinued(IEnumerable<Product> products, bool isDiscontinued)
{
    return products.Where(p => p.Discontinued == discontinued);
}

:

var query = Products.ByName("widget").AreDiscontinued(false);
+1

Source: https://habr.com/ru/post/1708372/


All Articles