How to execute a raw sql query from LINQ to Entities 4.5? - sql-server-2008-r2

Problem
I need to execute a raw SQL query from LINQ to Entities and retrieve the result. The query returns the current date/time from the SQL Server instance, and looks like this:
SELECT GETDATE()
[Edit]
I'm using a data model that was created database-first.
[/Edit]
What I've Tried
I've researched this issue on the interwebz and been unable to find a technique to do this. I was able to learn how to do this using LINQ to SQL, but since I'm not using that, it's of no help.

Heres what you are after
var time = context.Database.SqlQuery<DateTime>("SELECT GETDATE()").FirstOrDefault();
You can read more about raw sql and EF here http://msdn.microsoft.com/en-us/data/jj592907.aspx

Related

Converting SQL query with FORMAT command to use in entity framework core

I have an SQL query:
SELECT
FORMAT(datetime_scrapped, 'MMMM-yy') [date],
count(FORMAT(datetime_scrapped, 'MMMM-yy')) as quantity
FROM scrap_log
GROUP BY FORMAT(datetime_scrapped, 'MMMM-yy')
It basically summarises all the entries in the scrap_log table by month/year and counts how many entries are in each month/year. Returns two columns (date and quantity). But I need to execute this in an ASP.NET core API using Entity Framework core. I tried using .fromSqlRaw(), but this expects all columns to be returned and so doesn't work.
I can find plenty of info on EF to implement group by and count etc... But I cannot find anything for the FORMAT(datetime, "MMMM-yy") part. Please could somebody explain to me how to do this?
EDIT: Seems already I appear to be going about this the wrong way in terms of efficiency. I will look into alternative solutions based on comments already made. Thanks for the fast response.

On laravel using builder query whereRaw ?&

I have problem using query whereraw on laravel 5.5 postgresql, for this case i want to select data by colors. Data example
Source postgresql documentation postgres. I'm success to try on execute sql like this success example execute query. But fail using laravel example source code. Error on laravel
The problem is that your statement contains a question mark. When using the whereRaw method, the question mark is an expected parameter, which aren't providing in your call.
However it seems that there isn't a real solution for this issue. I suggest you take a look at Question mark operator in query, it handles about a similar issue.

Query Builder array_agg Laravel

I have a question about Laravel Eloquent ORM, can i use this tool to create Postgresql array_agg?, I have this query:
this query returns me:
[{"id":1, "contact_name":"name", "description":"description", "discharge":0, "latitude":null, "longitude":null, "town":null, "country":null, "province":null,
"numbers":"{77777,888888}", "emails":"{email#email.com, email2#email2.com}"}]
And im trying to create this query with eloquent: i have this code:
This second query returns me all the previous data except the numbers and emails, because i dont have any idea how to put array_agg in this query.
I appreciate any help!

SalesForce ADO.NET Source in SSDT 2013 SOQL Statement Using Date Literals Not Returning Results

I am having an issue with a date literal not returning any results when I run an SOQL query. The query is as follows:
Select * From dbo.Case WHERE CreatedDate = YESTERDAY
With the query, I would like to obtain case data from the previous day. I know there is data available that was created the previous day. The results of the query when I preview it, though, are an empty set with no error message.
A different wrinkle that makes this not quite a strict SOQL issue is that I am trying to use this query as an SQL command on an ADO.NET connection using the CData ADO.NET driver to connect to a SalesForce.com instance. My goal is to be able to build SSDT packages that will allow me to stage the data from SalesForce into our SQL Server for processing there.
I have similar issues using the LAST_N_DAYS date literal as well.
I believe I should be using SOQL to query in the SQL command text field for the ADO.NET source connection but I am not 100% sure about that. I know for certain that I cannot use T-SQL because it does not recognize the GETDATE().
Any guidance on how to pull the records from Case for the previous day or where the query I am using might be wrong would be greatly appreciated.
Found an answer. The following SQL command will pull the data from the previous day:
Select * From dbo.Case Where CreatedDate = 'YESTERDAY'
The single quotes evaluate the yesterday date literal as expected.
Likewise, the following SQL statement will get the last 30 days of data.
Select * From dbo.Case Where CreatedDate = 'LAST_N_DAYS:30'
Thanks to anyone who researched and attempted the question! :)

JPA: How to call a stored procedure

I have a stored procedure in my project under sql/my_prod.sql
there I have my function delete_entity
In my entity
#NamedNativeQuery(name = "delete_entity_prod",
query = "{call /sql/delete_entity(:lineId)}",
and I call it
Query query = entityManager.createNamedQuery("delete_entity_prod")
setParameter("lineId",lineId);
I followed this example: http://objectopia.com/2009/06/26/calling-stored-procedures-in-jpa/
but it does not execute the delete and it does not send any error.
I haven't found clear information about this, am I missing something? Maybe I need to load the my_prod.sql first? But how?
JPA 2.1 standardized stored procedure support if you are able to use it, with examples here http://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Stored_Procedures
This is actually they way you create a query.
Query query = entityManager.createNamedQuery("delete_entity_prod")
setParameter("lineId",lineId);
To call it you must execute:
query.executeUpdate();
Of course, the DB must already contain the procedure. So if you have it defined in your SQL file, have a look at Executing SQL Statements from a Text File(this is for MySQL but other database systems use a similar approach to execute scripts)
There is no error shown because query is not executed at any point - just instance of Query is created. Query can be executed by calling executeUpdate:
query.executeUpdate();
Then next problem will arise: Writing some stored procedures to file is not enough - procedures live in database, not in files. So next thing to do is to check that there is correct script to create stored procedure in hands (maybe that is currently content of sql/my_prod.sql) and then use that to create procedure via database client.
All JPA implementations do not support calling stored procedures, but I assume Hibernate is used under the hood, because that is also used in linked tutorial.
It can be the case that current
{call /sql/delete_entity(:lineId)}
is right syntax for calling stored procedure in your database. It looks rather suspicious because of /sql/. If it turns out that this is incorrect syntax, then:
Consult manual for correct syntax
Test via client
Use that as a value of query attribute in NamedNativeQuery annotation.
All that with combination MySQL+Hibernate is explained for example here.