Using sql queries in EF - c#

I am getting data from database in following way:
result = (from d in context.FTDocuments
join f in context.FTDocFlags on d.ID equals f.DocID into fgrp
from x in fgrp.DefaultIfEmpty()
where d.LevelID == levelID && x.UserID == userID && d.Status.Equals(DocumentStatus.NEW)
select new Entities.Document
{
ArrivalDate = d.ArrivalDate.Value,
BundleReference = d.BundleRef,
CreatedDate = d.CreatedDate,
CustomerID = d.CustomerID,
DocType = d.DocType.Value,
GuidID = d.DocGuid,
ID = d.ID,
LastExportID = d.LastExpID,
LevelID = d.LevelID,
ProfileID = d.ProfileID,
ScanDate = d.ScanDate.Value,
ScanOperator = d.ScanOperator,
SenderEmail = d.SenderEmail,
Status = d.Status,
VerifyOperator = d.VerOperator,
FlagNo = x == null ? 0 : x.FlagNo,
FlagUserID = x == null ? 0 : x.UserID
}).ToList();
Now, I am try to achieve this by using sql queries:
var test = context.Database.SqlQuery<string>("select *from FTDocument d left outer join FTDocFlag f on d.ID=f.DocID").ToList();
But get the following error:
The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types
Is it possible to use complex queries like above?
I use EF 6.0.

your query does not return a single string. Use like:
var test = context.Database.SqlQuery<Entities.Document>("...");

try this
const string query = #"select *from FTDocument d left outer join FTDocFlag f on d.ID=f.DocID";
var test = context.Database.SqlQuery<Entity>(query).ToList();

In my answer I have assumed EntitityFramework (ObjectContext) first, but then I have added the code for DbContext as well.
To check out the example below, you can use LinqPad and add your Entity Framework DLL by using EntitityFramework(ObjectContext) via Add connection. Specify connection properties and close the connection dialog. Then select the connection and run the example:
void Main()
{
var context=this; // requires that you selected an EF ObjectContext connection
var q=context.ExecuteStoreQuery<FTDocument>(
"SELECT * FROM FTDocument WHERE ID = #p0", 1);
q.ToList().Dump();
}
It will accept all kind of SQL queries, and you can use parameters like #p0, #p1 etc and simply append them comma-separated when you invoke the function ExecuteStoreQuery. The result will be returned as List<FTDocument>. To convert it to List<string> you need to specify which database field you want to return - or you create a comma-separated list of field values in each row, for example:
q.Select(s=>s.ID+", "+s.GuidID+", "+s.DocType).ToList().Dump();
The same example, but this time with EntityFramework (DbContext):
Add your Entity Framework DLL by using EntitityFramework(DbContext V4/V5/V6) via Add connection. Specify connection properties (don't forget to specify the AppConfig file) and close the connection dialog. Then select the connection and run the example:
void Main()
{
var context=this; // requires that you selected an EF DBContext (V4/5/6) connection
var q=context.Database.SqlQuery<FTDocument>(
"SELECT * FROM FTDocument WHERE ID = #p0", 1);
q.ToList().Dump();
}
Tip: Before you close the connection dialog, click Test. It will save you a headache later if you know the connection succeeds. For all those who want to try it out with a different EF project with your own database, here is a quick tutorial how to create it. Then simply replace FTDocument in the example above by a different table of your choice (in the SQL string and inside the brackets <...> of course).

Related

Build efficient SQL statements with multiple parameters in C#

I have a list of items with different ids which represent a SQL table's PK values.
Is there any way to build an efficient and safe statement?
Since now I've always prepared a string representing the statement and build it as I traversed the list via a foreach loop.
Here's an example of what I'm doing:
string update = "UPDATE table SET column = 0 WHERE";
foreach (Line l in list)
{
update += " id = " + l.Id + " OR";
}
// To remove last OR
update.Remove(update.Length - 3);
MySqlHelper.ExecuteNonQuery("myConnectionString", update);
Which feels very unsafe and looks very ugly.
Is there a better way for this?
So yeah, in SQL you've got the 'IN' keyword which allows you to specify a set of values.
This should accomplish what you would like (syntax might be iffy, but the idea is there)
var ids = string.Join(',', list.Select(x => x.Id))
string update = $"UPDATE table SET column = 0 WHERE id IN ({ids})";
MySqlHelper.ExecuteNonQuery("myConnectionString", update);
However, the way you're performing your SQL can be considered dangerous (you should be fine as this just looks like ids from a DB, who knows, better to be safe than sorry). Here you're passing parameters straight into your query string, which is a potential risk to SQL injection which is very dangerous. There are ways around this, and using the inbuilt .NET 'SqlCommand' object
https://www.w3schools.com/sql/sql_injection.asp
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand?view=dotnet-plat-ext-6.0
It would be more efficient to use IN operator:
string update = "UPDATE table SET column = 0 WHERE id IN (";
foreach (Line l in list)
{
update += l.Id + ",";
}
// To remove last comma
update.Remove(update.Length - 1);
// To insert closing bracket
update += ")";
If using .NET Core Framework, see the following library which creates parameters for a WHERE IN. The library is a port from VB.NET which I wrote in Framework 4.7 years ago. Clone the repository, get SqlCoreUtilityLibrary project for creating statements.
Setup.
public void UpdateExample()
{
var identifiers = new List<int>() { 1, 3,20, 2, 45 };
var (actual, exposed) = DataOperations.UpdateExample(
"UPDATE table SET column = 0 WHERE id IN", identifiers);
Console.WriteLine(actual);
Console.WriteLine(exposed);
}
Just enough code to create the parameterizing SQL statement. Note ActualCommandText method is included for development, not for production as it reveals actual values for parameters.
public static (string actual, string exposed) UpdateExample(string commandText, List<int> identifiers)
{
using var cn = new SqlConnection() { ConnectionString = GetSqlConnection() };
using var cmd = new SqlCommand() { Connection = cn };
cmd.CommandText = SqlWhereInParamBuilder.BuildInClause(commandText + " ({0})", "p", identifiers);
cmd.AddParamsToCommand("p", identifiers);
return (cmd.CommandText, cmd.ActualCommandText());
}
For a real app all code would be done in the method above rather than returning the two strings.
Results
UPDATE table SET column = 0 WHERE id IN (#p0,#p1,#p2,#p3,#p4)
UPDATE table SET column = 0 WHERE id IN (1,3,20,2,45)

SQLite query not executing properly in a WPF project

I'm working on a WPF application and using SQLite database. I can do every CRUD operation with Entity Framework, but in some specific cases I have to use raw SQL queries, and sometimes it's not returning what I need.
Here is a sample code:
using (var db = new DbContext(AppIO.DatabaseFilePath)) {
var key = 12;
string sql = $"SELECT COUNT(*) FROM SomeTable WHERE SomeField={key}";
var result = db.Database.ExecuteSqlCommand(sql);
}
I simplified the example. Here the result, what I got is -1. I copied the sql string value (after it's built) and executed in SQLiteStuido on the same database and it returned the correct value.
The DatabaseFilePath is correct. The connection is set correctly. I'm checking the same databases (in code and in SQLiteStudio). Any other idea?
Try this:
var result = db.Database.SqlQuery<int>(sql).First();
You have to call SqlQuery method and not ExecuteSqlCommand method. Since SqlQuery returns an IEnumerable you have to call Single. This is a the way to retreive scalar values from a query.
using (var db = new DbContext(AppIO.DatabaseFilePath)) {
var key = 12;
string sql = $"SELECT COUNT(*) FROM SomeTable WHERE SomeField={key}";
var result = db.Database.SqlQuery<int>(sql).Single();
}

c#, using dynamic queries

How can I use dynamic queries in C# ? From what I've searched its similiar to when we use SqlCommand with parameters to prevent sql injection(example below).
using (SQLiteConnection DB_CONNECTION = new SQLiteConnection(connectionString))
{
DB_CONNECTION.Open();
string sqlquery = "UPDATE table SET Name =#Name, IsComplete=#IsComplete WHERE Key =#Key;";
int rows = 0;
using (SQLiteCommand command = new SQLiteCommand(sqlquery, DB_CONNECTION))
{
SQLiteParameter[] tableA = { new SQLiteParameter("#Key", todo.Key), new SQLiteParameter("#Name", table.Name), new SQLiteParameter("#IsComplete", table.IsComplete) };
command.Parameters.AddRange(tableA);
rows = command.ExecuteNonQuery();
}
DB_CONNECTION.Close();
return (rows);
}
I'm new to c# and i wondering how can I make this work, thanks in advance.
Basically just build up the string sqlQuery based on a set of conditions and ensure that the appropriate parameters have been set. For example, here is some psuedo-C# (not tested for bugs):
//Set to true, so our queries will always include the check for SomeOtherField.
//In reality, use some check in the C# code that you would want to compose your query.
//Here we set some value we want to compare to.
string someValueToCheck = "Some value to compare";
using (SQLiteConnection DB_CONNECTION = new SQLiteConnection(connectionString))
{
DB_CONNECTION.Open();
string sqlquery = "UPDATE MyTable SET Name =#Name, IsComplete=#IsComplete WHERE Key =#Key";
//Replace this with some real condition that you want to use.
if (!string.IsNullOrWhiteSpace(someValueToCheck))
{
sqlquery += " AND SomeOtherField = #OtherFieldValue"
}
int rows = 0;
using (SQLiteCommand command = new SQLiteCommand(sqlquery, DB_CONNECTION))
{
//Use a list here since we can't add to an array - arrays are immutable.
List<SQLiteParameter> tableAList = {
new SQLiteParameter("#Key", todo.Key),
new SQLiteParameter("#Name", table.Name),
new SQLiteParameter("#IsComplete", table.IsComplete) };
if (!string.IsNullOrWhiteSpace(someValueToCheck)) {
//Replace 'someValueToCheck' with a value for the C# that you want to use as a parameter.
tableAList.Add(new SQLiteParameter("#OtherFieldValue", someValueToCheck));
}
//We convert the list back to an array as it is the expected parameter type.
command.Parameters.AddRange(tableAList.ToArray());
rows = command.ExecuteNonQuery();
}
DB_CONNECTION.Close();
return (rows);
}
In this day and age it would probably be worth looking into LINQ to Entities, as this will help you to compose queries dynamically in your code - for example https://stackoverflow.com/a/5541505/201648.
To setup for an existing database - also known as "Database First" - see the following tutorial:
https://msdn.microsoft.com/en-au/data/jj206878.aspx
You can skip step 1 since you already have a database, or do the whole tutorial first as practice.
Here is some psuedo-C# LINQ code to perform roughly the same update as the previous example:
//The context you have setup for the ERP database.
using (var db = new ERPContext())
{
//db is an Entity Framework database context - see
//https://msdn.microsoft.com/en-au/data/jj206878.aspx
var query = db.MyTable
.Where(c => c.Key == todo.Key);
if (!string.IsNullOrWhiteSpace(someValueToCheck))
{
//This where is used in conjunction to the previous WHERE,
//so it's more or less a WHERE condition1 AND condition2 clause.
query = query.Where(c => c.SomeOtherField == someValueToCheck);
}
//Get the single thing we want to update.
var thingToUpdate = query.First();
//Update the values.
thingToUpdate.Name = table.Name;
thingToUpdate.IsComplete = table.IsComplete;
//We can save the context to apply these results.
db.SaveChanges();
}
There is some setup involved with Entity Framework, but in my experience the syntax is easier to follow and your productivity will increase. Hopefully this gets you on the right track.
LINQ to Entites can also map SQL stored procedures if someone one your team objects to using it for performance reasons:
https://msdn.microsoft.com/en-us/data/gg699321.aspx
OR if you absolutely ust compose custom queries in the C# code this is also permitted in Entity Framework:
https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx

executing a complex sql select for postgresql using c# npgsql

I'm trying to execute a query that will get me a value from my postgre database using c# with the npgsql plugin. I got the query from here.
https://dba.stackexchange.com/a/90567
This is the query
string query = String.Format(#"SELECT a.attrelid::regclass::text, a.attname
, CASE a.atttypid
WHEN 'int'::regtype THEN 'serial'
WHEN 'int8'::regtype THEN 'bigserial'
WHEN 'int2'::regtype THEN 'smallserial'
END AS serial_type
FROM pg_attribute a
JOIN pg_constraint c ON c.conrelid = a.attrelid
AND c.conkey[1] = a.attnum
JOIN pg_attrdef ad ON ad.adrelid = a.attrelid
AND ad.adnum = a.attnum
WHERE a.attrelid = '""public.{0}""'::regclass
AND a.attnum > 0
AND NOT a.attisdropped
AND a.atttypid = ANY('{int,int8,int2}'::regtype[])
AND array_length(c.conkey, 1) = 1
AND ad.adsrc = 'nextval('''
|| (pg_get_serial_sequence (a.attrelid::regclass::text, a.attname))::regclass
|| '''::regclass)'; ", record);
It's giving me a
Input string was not in a correct format.
When it goes through that variable. I only have 1 variable and that's the {0}, but I don't know why it's yelling at me with that.
EDIT:
Btw, the double quotes(") are needed because it is created using entity framework and that's just how it works when you execute the query on pgAdminIII. All the tables needs to be inside them.

Find underlying tables of views using Linq to Entity to make Aggregate Dependencies

I have a function:
public static List<T> EntityCache<T>(this System.Linq.IQueryable<T> q, ObjectContext dc, string CacheId)
{
try
{
List<T> objCache = (List<T>)System.Web.HttpRuntime.Cache.Get(CacheId);
string connStr = (dc.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;
if (objCache == null)
{
ObjectQuery<T> productQuery = q as ObjectQuery<T>;
string sqlCmd = productQuery.ToTraceString();
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr))
{
conn.Open();
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sqlCmd, conn))
{
string NotificationTable = q.ElementType.Name;
System.Web.Caching.SqlCacheDependency sqldep = new System.Web.Caching.SqlCacheDependency(cmd);
cmd.ExecuteNonQuery();
objCache = q.ToList();
System.Web.HttpRuntime.Cache.Insert(CacheId, objCache, sqldep);
}
}
}
return objCache;
}
catch (Exception ex)
{
throw ex;
}
}
q can be a table, view or a procedure.
What i want is to find the underlying tables associated with a view or a procedure.
like if q is a join of tow tables i want to get the name of both the tables and finally
execute like:
If there are tw0 tables say A and B
Then i need to make Aggregate Dependency like:
string sqlCmd1 = string.Empty;
string sqlCmd2 = string.Empty;
using (testEntities ctx1 = new testEntities())
{
sqlCmd1 = ((System.Data.Objects.ObjectQuery)(from p in ctx1.A select p)).ToTraceString();
sqlCmd2 = ((System.Data.Objects.ObjectQuery)(from p in ctx1.B select p)).ToTraceString();
}
System.Data.SqlClient.SqlCommand cmd1 = new System.Data.SqlClient.SqlCommand(sqlCmd1, conn);
System.Data.SqlClient.SqlCommand cmd2 = new System.Data.SqlClient.SqlCommand(sqlCmd2, conn);
System.Web.Caching.SqlCacheDependency
dep1 = new System.Web.Caching.SqlCacheDependency(cmd1),
dep2 = new System.Web.Caching.SqlCacheDependency(cmd2);
System.Web.Caching.AggregateCacheDependency aggDep = new System.Web.Caching.AggregateCacheDependency();
aggDep.Add(dep1, dep2);
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
then the query i want to execute is
select * from A;
select * from B;
This i am using for SqlCacheDependency using Linq to Entity.
It works well for views when i hardcode the underlying tables but now i want the code automatically check for the underlying tables
and execute nonquery like
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
and make aggregate dependencies.
Any help is appreciated.
Thanks.
You must use database level tools to find which database objects your views or stored procedures depends on (but it also means you must know their full names in the database). For example SQL server offers sp_depends system stored procedure to track dependencies. This can be quite complicated because dependencies can have multiple levels (procedure can be dependent on view, view can be dependent on another view, etc.).
Be aware that advanced EF mapping also allows writing SQL directly to EDMX and in such case you will have to parse ToTraceString to find database objects.
I have found a solution for the problem i have posted.
There is a query that is valid for sql server 2005 onward.
We need to pass the name of the object and it will return us the name of the tables on which it depends
Example:
The name of the View is say AllProducts_Active_Inactive
;WITH CTE AS (SELECT o.name
, o.type_desc
, p.name
, p.type_desc as B
, p.object_id
FROM sys.sql_dependencies d
INNER JOIN sys.objects o
ON d.object_id = o.object_id
INNER JOIN sys.objects p
ON d.referenced_major_id = p.object_id
where o.name = 'AllProducts_Active_Inactive'
UNION ALL
SELECT o.name
, o.type_desc
, p.name
, p.type_desc as B
, p.[object_id]
FROM sys.sql_dependencies d
INNER JOIN CTE o
ON d.object_id = o.object_id
INNER JOIN sys.objects p
ON d.referenced_major_id = p.object_id
where o.name = 'AllProducts_Active_Inactive'
)
SELECT DISTINCT * FROM [CTE]
where B = 'USER_TABLE'
This post is the modified answer of the question i have posted on the website:
http://ask.sqlservercentral.com/questions/81318/find-the-underlying-tables-assocaited-with-a-view-or-a-stored-procedure-in-sql-server
What i changed is added the line where B = 'USER_TABLE'
Which means only those dependencies are returned who are tables.
And the seconds thing is added a WHERE clause so that a specific object is found.
Thanks

Categories

Resources