Dynamic linq: passing entire query as string - linq

Looking at Dynamic Linq, it's possible to use strings to define the key parts of the query. My question is, is it possible to pass the entire query in as a string?
ie: var foo = "from..."

LINQ stands for "Language INtegrated Queries" - it's compiled with the rest of the code, not parsed on the run. You can use Microsoft.CSharp.CSharpCodeProvider to compile your query on the run - but you will have to know in advance what local objects you want to send to the query.

That's not possible in dynamic LINQ -- dynamic LINQ only replaces specific pieces of the query. You can use ExecuteQuery on the data context in LINQ to SQL or SqlQuery on a DbSet<T>, though, to execute specific SQL commands.

Related

How to construct subquery in the form of SELECT * FROM (<subquery>) ORDER BY column;?

I am using gorm to interact with a postgres database. I'm trying to ORDER BY a query that uses DISTINCT ON and this question documents how it's not that easy to do that. So I need to end up with a query in the form of
SELECT * FROM (<subquery>) ORDER BY column;
At first glance it looks like I need to use db.QueryExpr() to turn the query I have into an expression and build another query around it. However it doesn't seem gorm has an easy way to directly specify the FROM clause. I tried using db.Model(expr) or db.Table(fmt.Sprint(expr)) but Model seems to be completely ignored and fmt.Sprint(expr) doesn't return exactly what I thought. Expressions contain a few private variables. If I could turn the original query into a completely parsed string then I could use db.Table(query) but I'm not sure if I can generate the query as a string without running it.
If I have a fully built gorm query, how can I wrap it in another query to do the ORDER BY I'm trying to do?
If you want to write raw SQL (including one that has a SQL subquery) that will be executed and the results added to an object using gorm, you can use the .Raw() and .Scan() methods:
query := `
SELECT sub.*
FROM (<subquery>) sub
ORDER BY sub.column;`
db.Raw(query).Scan(&result)
You pass a pointer reference to an object to .Scan() that is structured like the resulting rows, very similarly to how you would use .First(). .Raw() can also have data added to the query using ? in the query and adding the values as comma separated inputs to the function:
query := `
SELECT sub.*
FROM (<subquery>) sub
WHERE
sub.column1 = ?
AND sub.column2 = ?
ORDER BY sub.column;`
db.Raw(query, val1, val2).Scan(&result)
For more information on how to use the SQL builder, .Raw(), and .Scan() take a look at the examples in the documentation: http://gorm.io/advanced.html#sql-builder

LINQ Lambda Order in writing the query

I have the following query:
var query = db.Prog
.Where (a => a.Prog != "00000" && a.fn != "Koll")
.Select(a => new {a.Prog, a.MEfn})
.OrderByDescending(a => a.MEfn)
The query works fine but wondering if there are general rules on the order in which you write a Lambda linq query. Meaning, .Where comes before .Select, etc.
Can somebody enlighten me on the order in which LINQ needs to be written or best practices.
There isn't a best practice on the order in which you write a LINQ query, it will depend on if you want to do your filtering first, or your projection. For example in your case, you are projecting to an anonymous type which doesn't include the 'fn' property which your filter uses, so it wouldn't be available to use in a where clause if your select was first.
A better practice would be to give your properties less cryptic names. Also, 'fn' doesn't follow the PascalCase for property names, and if it's a field then it probably shouldn't be public.
Yours can be a good order.
Let's distinguish the case where db points to an SQL DB with a very good LINQ provider and the case db is an in-memory object. I guess it's the first.
In case you are using a LINQ to SQL provider, the statements are evaluated only when you materialize the query into an object, so the SQL optimizer (inside the DB) will take care of ordering of statements.
The vice versa occurs when your statements are run against in-memory collections or to materialized collections coming from LINQ to SQL. In that case they are executed sequentially, so you want to execute first those statements that reduce the number of results in the collection. Where is the best candidate!!!
The order that they should be in are completely dependent on the context of what you are doing. So if your OrderBy is simply formatting the data to be friendly to view, put it at the end after you have trimmed your collection, if your looking for the First value of a sorted collection then maybe you would need it before the collection is iterated to get the first.

Constructing dynamic linq queries based on user input

I am using dynamic linq on a project but don’t know how to run a particular query based on parameters. The example below shows the dynamic linq used to run 3 separate queries where a user has entered a filter expression or filer and sort expression etc. Without using if statements to check I (which seems incorrect and messy as I could end up with lots of if statements to cover the many different permutations ) I am unsure of how to generate the statements dynamically. Is this possible? I am running this query against Entity Framework.
context.Users.AsQueryable().Where(filterExpression)
context.Users.AsQueryable().Where(filterExpression).OrderBy(sortExpression)
context.Users.AsQueryable()Take(10).Where(filterExpression).OrderBy(sortExpression)
That should be achieved using expression tree only or may be using if..else clause
How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic)

Dynamic Query using Linq To SQL According Multiple Fields

Hi Experts
I have a special question About dynamic Linq to Sql.
Consider we want to search in a table according two fields*(LetterNo(string) and LetterDate(Datetime))*
.OK the problem is user can enter on of that fields or even both.
I searched in the internet and found "Linq.Dynamic" library in ScottGu weblog.but in that library if we want to use SqlParameter in exported command we should use #0 and param for that.problem is I don't know how many fields user entered.
I want use one query for that and no external tool like "Linq Kit PredicateBuilder".
If I create my query string Manually(and execute using ExecuteCommand) then I will abdicate SqlParameter and risk of Sql Injenction growing up.
How Can do that?
thanks
I suspect you are wanting to do something like the following:
IQueryable<Letter> query = context.Letters;
if (!string.IsNullOrEmpty(LetterNo))
query = query.Where(letter => letter.LetterNo == LetterNo);
If (LetterDate.HasValue)
query = query.Where(letter => letter.LetterDate == LetterDate);
When you execute query, it will combine the necessary expressions and issue a single query to the database based on the user's input.

Linq, what is difference in returning data in var, list, IEnumerable and IQueryable?

I am new to Linq please guide me on some basic things.
In read some articles on Linq. Some authers fill data in var from Linq query, some fills list of custom type objects and some fills data in IEnumerable and some do it in IQuryable. I could not get what is difference in these 4 and which one should be used in which situation.
I want to use Linq to SQL. What should I use?
Well, you can never declare that a method returns var - it's only valid for local variables. It basically means "compiler, please infer the static type of this variable based on the expression on the right hand side of the assignment operator".
Usually a LINQ to Objects query will return an IEnumerable<T> if it's returning a sequence of some kind, or just a single instance for things like First().
A LINQ to SQL or EF query will use IQueryable<T> if they want further query options to be able to build on the existing query, with the added bits being analyzed as part of the SQL building process. Alternatively, using IEnumerable<T> means any further processing is carried out client-side.
Rather than focusing on what return type to use, I suggest you read up on the core concepts of LINQ (and the language enhancements themselves, like var) - that way you'll get a better feel for why these options exist, and what their different use cases are.

Resources