Dynamic Query using Linq To SQL According Multiple Fields - linq

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.

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

How To Handle Pagination And Ordering In Cypher Query?

I am writing a cypher query in neo4j that merge few seperate queries with'UNION' operator. Now, the final result need to be sorted according to a specific column and I also need to be able to use 'LIMIT' to the final result so that I can fetch based on pagination request.
How to achieve that? adding 'ORDER BY' or 'LIMIT' at the end doesn't seems to work. Can't find a way to wrap the result as temporary set(as in sql queries) either. Any suggestions?
Currently it is not possible to add a ORDER BY or SKIP/LIMIT clause to the global set of UNION.
This is a pending feature request, see https://github.com/neo4j/neo4j/issues/2725
Maybe you can share your query and we can find a way to do it without UNION ?

What is the ElasticSearch equivalent for an SQL subquery?

Can you nest queries logically in ElasticSearch, so the output of one query is the input to another query.
Another, way to ask is how can I chain or pipe queries together?
This should be analogous to the IN operator or subqueries in SQL
i.e.:-
select au_lname, au_fname, title from
(select au_lname, au_fname, au_id from pubs.dbo.authors
where state = 'CA')
or
SELECT Name
FROM AdventureWorks2008R2.Production.Product
WHERE ListPrice =
(SELECT ListPrice
FROM AdventureWorks2008R2.Production.Product
WHERE Name = 'Chainring Bolts' );
Elasticsearch doesn't support subqueries; you would need to perform your first query, then construct a second query using the results of the first query as an input.
this is not supported in elastic-search you must normalize your data and have all field you need in one setting
That is totally correct, you must programm a subquery in your favorite programming language. An example can be found here:
https://sebastianviereck.de/elasticsearch-subquery-scoring-optimization/

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 linq: passing entire query as string

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.

Resources