i have the SQL Query in a string and am executing using the Traditional way of using DataAdapter.
Am trying to add pagination to the Existing logic. how do i add Skip take to the SQL string.
I know of using Skip and other linq methods for LINQ Queries. But is it possible to use for a SQL query in a string format.
If yes how do i do it without adding RowNum to the query rather use skip and take.
Eg :
String sqlQuery = Select * from tablename ;
SqlDataAdapter com = new SqlDataAdapter(sqlQuery, Connection);
How do i use Linq methods on this SQL query for pagination rather going for ROWNUM
*Am not sure if am repeating the Question but i was not able to identify with the keywords
Thanks
How do i use Linq methods on this SQL query for pagination rather going for ROWNUM
You can't. You're issuing direct SQL - LINQ isn't involved here. LINQ will translate a query written in C# into SQL, but you can't start adding bits of LINQ to an existing SQL query. You should decide whether you actually want to write SQL, or whether you want to use LINQ. Then do just one at a time.
(You can use both in the same project, sure - but for a single query, you can't mix and match.)
Related
I am using Fluent NHibernate to query data stored in a SQL Server temporal table. All I really want to do is to run a query such as
SELECT * FROM [MyDB].[dbo].[MyTable] for system_time as of '2022-12-28T21:00:00.0000000' where ...
Via NHibernate. It doesn't seem like there's any way built in to NHibernate that can run that query. I can run queries such as below but that only hits the current table, and not the history table.
session.QueryOver<MyDTO>().Where(x => x.TemporalPeriodStart > ...)
You can execute native SQL queries (and return non managed entities).
The query needs to specify:
Query String
A Result transformer
Example:
session.CreateSQLQuery("SELECT * FROM [MyDB].[dbo].[MyTable] for system_time as of '2022-12-28T21:00:00.0000000' where...")
.SetResultTransformer(Transformers.AliasToBean(typeof(CustomObject)))
Worth noting that the custom IResultTransformer should override "Equals" and "GetHashCode", otherwise a memory leak is possible since query translation won't be cached.
You can also use Named SQL query, which can be defined in the mapping document and called in the same way as a named HQL query...
Hi all i'm currently working in ASP.NET using the query builder to create select, insert, update queries etc etc on some datasets which i have created in my App_Code folder. I have realised for you to use a parameters in the queries you have to use a "?" like so
SELECT * FROM users WHERE email = ?
what i was wondering is does this actually protect your tables from sql injection or do you need to do more in the code in order to protect the queries?
Parameterized queries accept parameters and input them as the appropriate SQL data type. So for example creating this proc
CREATE PROCEDURE GetStudent (IN LN VARCHAR(200))
BEGIN
SELECT Name FROM Students WHERE LastName = LN;
END
And passing this value (assume this is in your C# code.
"'Bobby'; DROP TABLE STUDENTS;"
Will essentially execute this query
SELECT Name FROM Students WHERE LastName ='''Bobby;''DROP TABLE Students'
Which is quite safe.
Of course, you will have to adapt for your particular application needs, but the general point is that parameterized queries are safe against SQL Injection for all major RDMSs.
I'm using LINQ To Sql (not Entity Framework), the System.Data.Linq.DataContext library, hitting a SQL Server 2005 database and using .Net Framework 4.
The table dbo.Dogs has a column "Active" of type CHAR(1) NULL. If I was writing straight SQL the query would be:
SELECT * FROM dbo.Dogs where Active = 'A';
The LINQ query is this:
from d in myDataContext.Dogs where d.Active == 'A' select d;
The SQL that gets generated from the above LINQ query converts the Active field to UNICODE. This means I cannot use the index on the dbo.Dogs.Active column, slowing the query significantly:
SELECT [t0].Name, [t0].Active
FROM [dbo].[Dog] AS [t0]
WHERE UNICODE([t0].[Active]) = #p1
Is there anything I can do to stop Linq to Sql from inserting that UNICODE() call (and thus losing the benefit of my index on dogs.Active)? I tried wrapping the parameters using the EntityFunctions.AsNonUnicode() method, but that did no good (it inserted a CONVERT() to NVARCHAR instead of UNICODE() in the generated sql), eg:
...where d.Active.ToString() == EntityFunctions.AsNonUnicode('A'.ToString());
Linq is meant to make it easier to write queries and does not always generate optimal SQL. Sometimes when high performance is required it is more efficient to write raw SQL directly against the database, the Linq datacontext supports mapping of SQL result to entities just like linq.
In your case I would suggest writing:
IEnumerable<Dog> results = db.ExecuteQuery<Dog>(
"SELECT * FROM dbo.Dogs where Active = {0}",
'A');
This is an old question, but I bumped into this recently.
Instead of writing
from d in myDataContext.Dogs where d.Active == 'A' select d;
Write
from d in myDataContext.Dogs where d.Active.Equals('A') select d;
This will produce the desired SQL without having to resort to any of the "hacks" mentioned in other answers. I can't say why for certain.
I've posted that as a question, so we'll see if we get any good answers.
There's not much you can do to the way LINQ queries are translated into SQL statements, but you can write a stored procedure that contains your queries and call that SP as a LINQ2SQL function. This way you should get full benefit of SQL Server optimizaions
You can do a little hack (as it is often required with LINQ to SQL and EF). Declare the property as NCHAR in the dbml. I hope that will remove the need to do the UNICODE conversion. We are tricking L2S in a benign way with that.
Maybe you need to also insert the EntityFunctions.AsNonUnicode call to make the right hand side a non-unicode type.
You can also try mapping the column as varchar.
I have a DataTable, and need to extract the data by using this SQL query:
SELECT code_direction, count(TP) AS CN FROM table1 WHERE
cod_time = 'A011' GROUP BY TP,code_direction;
Which is the C# LINQ equivalent query?
After it I want to move the results into a new DataTable.
I tried many examples founded around in web but no this specific logic.
Linqer is your friend!
This tool can translate SQL to LINQ. You can download it at http://www.sqltolinq.com.
Note that it's not always possible to convert a SQL query straight into a 100% equivalent LINQ query, but it should be close enough.
If you need translation in the other direction -- from LINQ to SQL -- you can use LINQPad. Download it at http://www.linqpad.net/.
Is there a way to see final query which is passed to SQL Server database from my C# app ?
For ex I got query:
SELECT * FROM mytable WHERE x = #yyyy;
This creates and SQLCommand object
SqlCommand cmd = new SqlCommand("SELECT * FROM mytable WHERE x = #yyyy");
Plus I need to pass parameter:
cmd.Parameters.Add("#yyyy","MyValue");
What I want to see (in debug in C# or somewhere in SQL Server Management Studio) is this:
SELECT * FROM mytable WHERE x = MyValue
Where can I find such query ?!
Best regards
Where can I find such query ?!
You can't. Such a query never exists. The values are not substituted into the SQL.
I think actually sp_executesql is called, and this function accepts the parameters separately from the SQL. You can check this using SQL Profiler to see the actual SQL.
Update:
ORDER BY #descOrAsc
Your problem is that parameters can only be used in certain places where expressions are allowed. DESC is not an expression - it is a reserved word. You cannot use a parameter containing the string "DESC" instead of writing the keyword DESC in the query.
Also, you haven't specified which column to order by.
You can run the SQL Server Profiler and see all the queries that get executed, to see whats happening (and copy paste these into the Sql Server Management Studio to do tests etc)
I would expect the query to be passed to SQL Server with the parameters. There should be no need for anything to ever create a full SQL-only query. It makes no sense to do so, as it just means more conversions for either the client, the server or both. On the server side, the query processor is going to want to parse the query into clauses with values - if the command can pass those values directly, where's the advantage on converting them into the SQL statement, only to have the server parse them into separate values again?
1.You can use SQL Profiler. (here you can see all process)
2.You can write all your queries to SQL Server table. And then you can always get queries from this table.