Retrieve data using Dynamic Query and Linq to SQL - sql

Hi I have a really complicated dynamic query
that i want to use to retrieve data from the database
I am working in .net 3.5 sql server 2008
i created a stored procedure that accepts a varchar(max) as input parameter and does
execute (#SqlQuery)
it executes but does not return anything
I really would like to use LINQ as all my project is implemented using linq
Any Idea how to do it
what is the problem?

If you want to execute raw SQL via LINQ, you should look into the method ExecuteQuery<T>.

using (SqlConnection con = new SqlConnection("server=(local)\\SQLEXPRESSdatabase=MyDatabase;Integrated Security=SSPI"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = #sqlcommand actualtext;
cmd.Parameters.Add(anyParams that are in the query);
con.open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
//code here reader should have all the data returned that met the select statement
}
}
}

Related

How can I call stored procedure result into view model asp.net core

How can I call the stored procedure into view model
SqlParameter paruserID = new SqlParameter("#UserID", userId);
SqlParameter paryear = new SqlParameter("#LogYear", lockyear);
SqlParameter parmonth = new SqlParameter("#LogMonth", lockmonth);
var result = _db.Database.SqlQuery<AttendanceViewModel>("EmpProcedure", paruserID ,paryear ,parmonth
The Database.SqlQuery method is not provided in EF Core. If you'd like to execute a stored procedure, you can try to use the FromSqlRaw extension method, like below.
var result = _db.Attendance.FromSqlRaw("EXEC EmpProcedure #UserID, #LogYear, #LogMonth", parameters)
.ToList()
.Select(u => new AttendanceViewModel
{
UserID = u.UserID,
LogYear = u.LogYear,
LogMonth = u.LogMonth
//other fields
//...
}).FirstOrDefault();
For more information about executing Raw SQL Queries, you can check following doc:
https://learn.microsoft.com/en-us/ef/core/querying/raw-sql
Besides, the DbContext.Database property provides an API that allows us to perform ADO.NET operations directly, you can also use following code snippet to execute your stored procedure.
using (var command = _db.Database.GetDbConnection().CreateCommand())
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "EmpProcedure";
command.Parameters.Add(new SqlParameter("#UserID", userId));
command.Parameters.Add(new SqlParameter("#LogYear", lockyear));
command.Parameters.Add(new SqlParameter("#LogMonth", lockmonth));
_db.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
// ...
// code logic here
// do something based on your actual requirement
}
}
For more information about leveraging ADO.NET via the Context.Database property, please check:
https://www.learnentityframeworkcore.com/raw-sql#leveraging-ado.net-via-the-context.database-property

To String Conversion while doing Join in LINQ

I am using LINQ query to fetch the data from database and also doing joins in the LINQ query as,
(
from accountTransaction in AccountTransactions
join xlkpQualifier in Enumerations on
accountTransaction.LkpQualifier.ToString() equals xlkpQualifier.Value
select top accountTransaction)
.Take(10);
I am getting Exception on accountTransaction.LkpQualifier.ToString() that System.ToString() can't be used in LINQ Entities.
But I am getting problem here in conversion to string on Join.
How can I do it?
Until you provide us with some more information on the SQL types of the fields LkpQualifier and xlkpQualifier, I will answer as follows:
You should either (1) change your table data schema and set the same data types or (2) write the raw SQL version of your LINQ query and execute the query
Raw SQL query using EF:
using (var db = new Entities())
{
string myQuery = "SELECT * FROM Table";
var result = new ObjectQuery<DbDataRecord>(myQuery, db);
var resultList = result.ToList();
}
In the raw SQL query itself, you will probably have to use the CAST function with the right type:
CAST(Enumerations.xlkpQualifier AS System.Int32)
Raw SQL query without using EF:
There is also a way to write raw SQL without using EF (useful when your table doesn't have the primary key set and you don't have access to change that):
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Table";
var result = cmd.ExecuteScalar(); // or other variations
}
}

SQL - OleDbCommand not changing Sql Parameter

Below is the code for my Select * Function - It WORKS well and does everything great until i change the SQL string from Select * From Company to
query = "Select * From #1";
and then do the following
query = "Select * From #1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);
DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;
//Add Parameters
Command.Parameters.AddWithValue("#1", SQLTables.Company);
try
{
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
}
return Table;
The DBMS keeps sending back "Query incomplete" - I assume The Command variable is sending the string query through without changing the Parameter from #1 to Company
Here is a piece of code (mine) where this does work. This is an insert statement rather that a select - Correct me if i am wrong but should it not also work with the SELECT aswell
private void MainActionsInsert(string Action, bool Checked)
{
OleDbCommand Command = new OleDbCommand("INSERT INTO MainActions Values (ID, Action, BoolValue)", DataBaseConnection);
//Add Parameters
Command.Parameters.AddWithValue("ID", GenerateID());
Command.Parameters.AddWithValue("Action", Action);
Command.Parameters.AddWithValue("BoolValue",Checked);
//Add Command
MainActionsAdapter.InsertCommand = Command;
//Execute Agains DataBase
Command.ExecuteNonQuery();
//Accept Changes
}
`
OLEdb doesn't recognize named parameters. You must use ? in the query text.
However, you also can't use dynamic table names with parameterized queries, so even using a ? will not help.
You need to use full dynamic SQL, though that can open you up to SQL Injection. Make sure you read the full article I linked.
OleDbCommand Does accept Parameterized SQL just not in the From Clause - It Has to be either in a WHERE clause or something like that. Like you said it Worked with the insert function because it expects "parameters" there. For example this will work
query = "Select * From Company Where #param = 1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);
DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;
//Add Parameters
Command.Parameters.AddWithValue("param", "ID");
try
{
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
}
return Table;
Funny though that it doesn't work for the Select part though

Writing values to sql database

I am trying to write three variables into a database table. The code I have is:
sqlCmd.CommandText = "INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(StudentNumber.ToString() , Time.ToString() , Total.ToString())" + dbConnection;
sqlCmd.ExecuteNonQuery();
sqlTran.Commit();
dbconnection is the name of the connection. It does not do anything. It is in a try-catch but goes straight to catch.
Thanks in advance.
You should
avoid concatenating together your SQL statement - avoid SQL injection attacks! Use parametrized queries instead!
use using blocks for your SqlConnection and SqlCommand objects
Try something like this:
string _connString = "........";
string queryStmt =
"INSERT INTO dbo.PortfolioValues(StudentNumber, TimeStamp, PortfolioValue) " +
"VALUES(#StudentNumber, #TimeStamp, #TotalValue)";
using(SqlConnection _con = new SqlConnection(_connString))
using(SqlCommad _cmd = new SQlCommand(queryStmt, _con))
{
// create paramters and set values
_cmd.Parameters.Add("#StudentNumber", SqlDbType.Int).Value = StudentNumber;
// do the same for the other two parameters
try
{
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
catch(Exception exc)
{
// handle exception
}
}
StudentNumber.ToString() cannot be contained in a query! It's java code not sql...
//Am asuming you are using C# and the System.Data.SqlClient
//here is how you might do what you want
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
//so that you use it this way:
String query = String.Formart("INSERT INTO dbo.PortfolioValues(StudentNumber,TimeStamp,PortfolioValue) VALUES(\"{0}\",\"{1}\",\"{2}\")",StudentNumber.ToString() , Time.ToString() , Total.ToString());
String connectionString = "your connection string";
CreateCommand(query,connectionString);

ExecuteReader returns no results, when inspected query does

Consider the following code:
StringBuilder textResults = new StringBuilder();
using(SqlConnection connection = new SqlConnection(GetEntityConnectionString()))
{
connection.Open();
m.Connection = connection;
SqlDataReader results = m.ExecuteReader();
while (results.Read())
{
textResults.Append(String.Format("{0}", results[0]));
}
}
I used Activity Monitor within Sql Server Mgmt Studio on the database to inspect the exact query that was being sent. I then copied that query text to a query editor window within SSMS, and the query returned the expected results. However, SqlDataReader results is always empty, indicating "The enumeration returned no results."
My suspicion is that somehow the results are not being returned correctly, which makes me think there's something wrong with the code above, and not the query itself being passed.
Is there anything that would cause this in the code above? Or something I've overlooked?
EDIT:
Here is the query as indicated by the SQLCommand object:
SELECT DISTINCT StandardId,Number
FROM vStandardsAndRequirements
WHERE StandardId IN ('#param1','#param2','#param3')
ORDER BY StandardId
Here is the query as it appears in Activity Monitor:
SELECT DISTINCT StandardId,Number
FROM vStandardsAndRequirements
WHERE StandardId IN ('ABC-001-0','ABC-001-0.1','ABC-001-0')
ORDER BY StandardId
The query is working against a single view.
When I ran the second query against the database, it returned 3 rows.
The SqlDataReader indicates 0 rows.
try to use Sqldata adapter instead of sqldatreader.
StringBuilder textResults = new StringBuilder();
using (var conn = new SqlConnection(GetEntityConnectionString())))
{
using (
var cmd = new SqlCommand(
"SELECT DISTINCT StandardId,Number" +
"FROM vStandardsAndRequirements " +
"WHERE StandardId IN (#param1,#param2,#param3)" +
"ORDER BY StandardIdl"
, conn))
{
var dSet = new DataSet();
var dt = new Datatable();
var da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#param1", SqlDbType.VarChar, 50).Value = "ABC-001-0";
cmd.Parameters.Add("#param2", SqlDbType.VarChar, 50).Value = "ABC-001-0.1";
cmd.Parameters.Add("#param3", SqlDbType.VarChar, 50).Value = "ABC-001-0";
try
{
da.Fill(dSet);
dt = dSet.Tables[0];
foreach(Datarow a in dt.Rows)
{
textResults.Append(a["StandardId"].tostring()).AppendLine();
}
Messabox.Show(textResults.tostring);
}
catch (SqlException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
Regards.
Are you sure it is
WHERE StandardId IN ('#param1','#param2','#param3')
instead of this?
WHERE StandardId IN (#param1,#param2,#param3)
Parameters should not be quoted, not in the SQLCommand object.
Very nice behavior I've observed
I looked for errors in code:
... dr = command.ExecuteReader() ... If dr.Read Then ...
and found that 'dr.Read' works fine, but...
when I mouseover on 'dr', to lookup for data, return values disappeared !
Check your connection string and make sure you are not connecting as a user instance.
http://msdn.microsoft.com/en-us/library/ms254504.aspx