Here's the lambda expression, I want to convert this to SQL Server query syntax.
{x => ((True AndAlso x.Name.ToLower().Contains("_")) AndAlso Not(x.IsDeleted))}
Note : The lambda expression is equivalent to Where Clause of Sql server.
I want to convert it to sql syntax and then pass it to sql server stored procedure.
Is there any way I can achieve this?
Generally, you can use the ToString method on the IQueryable object returned by the LINQ statement to find the exact query that would be executed on the database. But, in this case, I would guess something like this might be generated for the WHERE:
WHERE CONTAINS(Name, '_') AND NOT IsDeleted
But, you haven't provided any detail that would allow me to verify that.
If you don't have full-text on, then the following might be more applicable:
WHERE Name like '%_%' AND NOT IsDeleted
Related
I have the most bizarre issue with EF Core 3.1. In EF Core 2.2 I used to be able to execute stored procedures. I see there is a breaking change in the documentation but, I am following the documentation exactly and it is not working. I have no nulls anywhere in the returned data. The NoticeOfInspection object matches the returned data exactly. What on Earth did they change that this is not working?
var data = _dbContext.NoticeOfInspections.FromSqlRaw("EXEC dbo.NewReportApp_NoticeOfInspection {0}", FacilityId).Single();
The error message is not helpful at all. First with the above line, it says, "InvalidOperationException: FromSqlRaw or FromSqlInterpolated was called with non-composable SQL and with a query composing over it. Consider calling AsEnumerable after the FromSqlRaw or FromSqlInterpolated method to perform the composition on the client side."
What?
So, I add AsEnumerable and then it throws, "InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'."
What on Earth have they done. This is not intuitive at all.
FromSqlRaw or FromSqlInterpolated was called with non-composable SQL
The non-composable SQL is the one which cannot be converted to subquery select * from (your_sql). Calling SP (EXEC …) is one of the non-composable constructs.
and with a query composing over it
Non query returning LINQ operators like Single, First, Count, Max, Sum etc. require composing over the provided SQL query, for instance select count * from (your_query).
You can read more about it in Raw SQL queries - Composing with LINQ documentation topic, which also contains the "calling SP" and other limitations/restrictions:
Composing with LINQ requires your raw SQL query to be composable since EF Core will treat the supplied SQL as a subquery. SQL queries that can be composed on begin with the SELECT keyword. Further, SQL passed shouldn't contain any characters or options that aren't valid on a subquery, such as:
A trailing semicolon
On SQL Server, a trailing query-level hint (for example, OPTION (HASH JOIN))
On SQL Server, an ORDER BY clause that isn't used with OFFSET 0 OR TOP 100 PERCENT in the SELECT clause
SQL Server doesn't allow composing over stored procedure calls, so any attempt to apply additional query operators to such a call will result in invalid SQL. Use AsEnumerable or AsAsyncEnumerable method right after FromSqlRaw or FromSqlInterpolated methods to make sure that EF Core doesn't try to compose over a stored procedure.
With that being said, inserting AsEnumerable() before Single() should really work.
The new exception you are getting is either EF Core bug or data type mapping issue (either you are passing int to string parameter, or SP is returning int for string class property). You need to examine the exception stack trace and/or compare your SP parameter and column types to FacilityId argument type and NoticeOfInspection class property types/mappings.
I have a JPA Repository with a few custom queries. I've been tasked with implementing a functionality which requires numerous new queries. One thing that would drastically cut down on the number of them is if I could use a wildcard for a boolean value.
I have tried modifying the query to use 'LIKE %' but Spring Data doesn't like it, throwing a numberFormatException (Infinite of NaN).
The original query:
#Query("SELECT SUM(paymentSummary.paidAmount) FROM InvoiceLineItem invoice INNER JOIN PaymentSummary paymentSummary"
+ " ON invoice.invoiceKey=paymentSummary.invoiceKey"
+ " WHERE invoice.balanced=:balanced")
BigDecimal getInvoicePaidTotalByBalanced(#Param("balanced") boolean balanced);
Ideally, I'd like to use the same query, but instead of passing it true or false, I'd pass it a wildcard so that it acted on all records regardless of the true/false status.
As of now, the only way I know how to do this is to create a second query, same as the first, minus the where clause.
How about using the IN operator instead? (TRUE, FALSE) will then be your wildcard.
Alternatively, you should be able to use WHERE :balanced IS NULL OR invoice.balanced=:balanced. In that case, change boolean to Boolean and null becomes the wildcard.
I'm writing a Dropwizard app that needs to connect to the database, and using SQL objects to query the DB, per the Dropwizard docs.
The issue I'm running into is when my query is using a type specifier (::) being confused for a binding variable. Something like
SELECT
(a,
b,
c)::user_type
FROM ...
WHERE id = :id
The parser is reading ::user_type as a parameter placeholder. When I've escaped them with \, it says the query is not returning any rows, but if I run the query through psql, it does, so I'm guessing it's not so simple. Any help would be appreciated.
Thanks! :D
The easiest solution is to just use the SQL-standard CAST syntax not the PostgreSQL extension :: syntax.
CAST (c AS user_type)
I am using JPA native query to call a stored procedure and map the return result to a class
createNativeQuery(String sqlString, Class resultClass);
Here sqlString is a stored procedure in this format:
{call storeProcedureName parameter1, paramter2, parameter3}
I noticed that when one of the parameter contains a forward slash (/), the result result will be wrong. Has any body encountered this problem before and how to solve it? thanks
I am using EclipseLink and glassfish server.
Are you in-lining the parameters into your SQL, or using parameters on your query? You should use parameters on your query, in-lining parameters into SQL is very bad (can lead to SQL injection attacks).
See,
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Native#Parameters
I have ADO.NET EF expression like:
db.Table1.Select(
x => new { ..., count = db.Table2.Count(y => y.ForeignKey.ID == x.ID) })
Does I understand correctly it's translated into several SQL client-server requests and may be refactored for better performance?
Thank you in advance!
Yes - the expression will get translated (in the best way it can) to a SQL query.
And just like any T-SQL query, an EF (or L2SQL) query expression can be refactored for performance.
Why not run SQL profiler in the background to see what it is getting executed, and try and optimize the raw T-SQL first - which will help optimize the expression.
Or if you have LinqPad, just optimize the T-SQL query and get LinqPad to write your query for you.
Also, im not really sure why you have specified the delegate for the Count() expression.
You can simply do this:
var query= from c in db.Table1
select new { c.CustomerID, OrderCount = c.Table2s.Count() };
The answer is NO - this query will be translated into one client-to-RDBMS request.
RPM1984 advised to use LinqPad. LinqPad showed that the query will be translated into very straightforward SQL expression. Approach with grouping will be translated into another SQL expression but still will be executed in one request.