Map Stored Procedure Result without Columns to a Model - c#

I have a stored procedure that returns two columns without specifying their name, one is the ID (int) and the other one is a string. It is not possible for me to alter the stored procedure so that it can return the results with column names
If I let Visual Studio to create the .edmx file with the stored procedures in the dbContext, it creates a new model class with two properties called Column1 and Column2. The problem is that when I run it, I receive the following error:
The data reader is incompatible with the specified 'Schema.addCliente_Result'. A member of the type, 'Column1', does not have a corresponding column in the data reader with the same name.
Is there any other way to map the result to maybe a a dictionary<int,string> or anything else that does not need the column name?

You can try using KeyValuePair. It saves the value specified for your key. You can create list of KeyValuePair if you have more pairs and you want to iterate through it easier. I'm not sure if this helps in your case, sorry if it's not helping.
KeyValuePair MSDN

Perhaps you may want to consider projection since you don't want it mapped to a Model. Projection is when the result of a query is output to a different type than the one queried. Either way, you can use the results of the stored procedure to either create an anonymous type or a class of your own. Since there's no code for me to reference, I have an example as follows:
Class used to store results
public Class Result
{
public int myID {get; set;}
public string myString {get; set;}
}
Code to call stored procedure
string connectionString = ConfigurationManager.AppSettings["MyDatabase"];
var conn = new SqlConnection(connectionString);
conn.Open();
string query = #"my_stored_procedure";
using (var sqlAdpt = new SqlDataAdapter(query, conn))
{
sqlAdpt.SelectCommand.CommandType = CommandType.StoredProcedure;
// Ex: Parameters if your sp takes one
var dataDate = new SqlParameter { ParameterName = "#DataDate", Value = DateTime.Now };
sqlAdpt.SelectCommand.Parameters.Add(dataDate);
var results = new DataSet();
sqlAdpt.Fill(results);
List<Result> resultList = results.Tables[0].AsEnumerable().
Select(dataRow => new Result
{
myID = dataRow.Field<int>("ID"),
myString = dataRow.Field<string>("column_I_cant_change")
}).ToList();
}

Related

Store query results into object

I try to read sql table and load all into a variable
Code:
String query2 = "";
query2 = String.Format("SELECT * FROM Seguridad.UsuarioPerfil WHERE UsuarioID = {0}", UsuarioID);
SQLService sqlservice2 = new SQLService();
DataTable reader2 = sqlservice.Leer(query2);
I want to store all data into a variable var tmpPerfiles as object.
I can do something like:
var tmpPerfiles ="";
foreach (DataRow row in reader.Rows)
{
tmpPerfiles = row["UsuarioId"].ToString();
tmpPerfiles = row["PerfilId"].ToString();
}
But I canĀ“t call tmpPerfiles two times. How can I achieve that? Regards
Okay, first up: STOP! Do not EVER write SQL queries like this. SQL Injection Attack is still the #1 cause of security breaches and vulnerabilities (per OWASP), and it's exclusively caused by people writing SQL statements like this.
Never ever write SQL statements like:
statement = "SELECT something from sometable where " + someVar ...
... because all it takes is for that 'somevar' to have an apostrophe and some malicious hacking code, and you're granting an external entity access to your database. Don't even do it if you're not expecting the field to be user-provided or such - it's a bad habit, and it leads to horrendous security faults.
Instead, you should always use one of the following:
Stored Procedures with parameterized inputs. Aka, dbo.usp_FindUser,
which accepts #userName, and the proc has WHERE name = #userName
Parameterized Sql Command. Aka, creating a SqlCommand with "Select *
from something from someTable where userName = #userName", and then
adding a parameter to the SqlCommand of userName, and a value of what
user you're looking for.
Okay, all that said?
Keep in mind, a variable can contain a grouping of things. Generally, if you're looking to contain a table within a single variable? It'll typically look something like:
string x, int y, string z - fields within the Database
Class dataRecord - a class, which contains string x, int y, string z.
List<dataRecord> - a list of instances of a dataRecord class
... make sense? You've got one variable per column, which you group into a class. One instance of the class represents one data row. And then a List<> of that class represents multiple rows of that table (or just the whole table itself.)
Usually, code that follows SRP (but that doesn't use EntityFramework) will look something like:
List<myFancyClass> tableEntries = new List<myFancyClass>();
foreach (DataRow dr in myDataTable.Rows)
{
myFancyClass line = new myFancyClass(dr); // constructor that takes in a DataRow
tableEntries.Add(line);
}
... at that point, the table is stored in the tableEntries variable.
e.g.
use a dto for storing it into a list
private class TmpDto {
string UsuarioId { get; set;}
string PerfilId { get; set;}
}
var Ilist<TmpDto> list = new List<TmpDto>();
foreach (DataRow row in reader.Rows)
{
var dto = new TmpDto();
dto.UsuarioId = row["UsuarioId"].ToString();
dto.UsuarioId = row["PerfilId"].ToString();
list.Add(dto);
}
so you have several objects stored within a list
If you are using EntityFramework, this is really easy. After setting up a class for the object (containing all fields), just use linq to get the object.
var myData = UsuarioPerfil.Where(e => e.UsuarioID == UsuarioID).FirstorDefault();
If all you want to do is get values from a database and put them into something, then I think the introduction of a datatable is overkill. While the implementation is easy enough, it adds overhead. I'd opt to use a DbDataReader instead.
This is an example of extracting a single field, and then just adding it to a list.
List<string> results = new List<string>();
String query2 = "SELECT PerfilId FROM Seguridad.UsuarioPerfil WHERE UsuarioID = #USARIO";
SqlCommand cmd = new SqlCommand(query2, connection);
cmd.Parameters.Add(new SqlParameter("#USARIO", SqlDbType.VarChar));
cmd.Parameters[0].Value = UsuarioID;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
results.Add(reader.GetString(0));
}
reader.Close();
You referenced two fields, but since UsuarioID was defined in the where clause, it didn't seem necessary to pull it back.
Also, as #DotNetDev mentioned, don't use literals... the use of parameters is not only SQL-Injection safe, but it's more scalable and actually friendlier to the database (compile-once, execute many).
Finally, if you want to pull back multiple fields, create a data (domain) object, and make your results a list of that object. If you need an example, feel free to ask.

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

How to retrieve table dynamically using only one controller?

I am using the following code as a controller for a single table to access the table from my database, and assign values of each column to a variable. However, I have many tables(Booktrans in this case) and I want to use a single controller that can access all the tables using table ID as a variable. After that, assigning values of different columns from different tables will also be different from the code below. Could anyone help me with a "dynamic" way of coding to replace this controller for a specific table with a dynamic controller?
I am using MVC4.
All the tables have different structures and different column names.
public ActionResult Booktrans()
{
String connectionString = "Dsn=SECURE;Uid=internwebuser";
OdbcConnection conn = new OdbcConnection(connectionString);
String sql = "SELECT * FROM booktrans";
OdbcCommand cmd = new OdbcCommand(sql, conn);
var model = new List<Booktrans>();
using (conn)
{
conn.Open();
OdbcDataReader rdr = cmd.ExecuteReader();
//model = new List<Booktrans>();
while (rdr.Read())
{
var book = new Booktrans();
book.ship_last_name = rdr["ship_last_name"].ToString();
book.ship_first_name = rdr["ship_first_name"].ToString();
book.ship_zip = rdr["ship_zip"].ToString();
book.ship_state = rdr["ship_state"].ToString();
book.ship_address = rdr["ship_address"].ToString();
book.ship_city = rdr["ship_city"].ToString();
book.day_phone = rdr["day_phone"].ToString();
book.email_address = rdr["email_address"].ToString();
model.Add(book);
}
}
return View(model);
}
How about you use an actual ORM, since that's what you're trying to reverse-engineer here. With something like Entity Framework, you create an entity class that maps to a particular table and that has properties that map to columns in that table. Then, with Entity Framework, in particular, you add a DbSet that represent the collection of rows in this table to your context:
public DbSet<Foo> Foos { get; set; }
With that, you can then simply use the API Entity Framework provides to interact with that data:
// Get specific Foo
var foo = db.Foos.Find(id);
// Get matching Foos
var foos = db.Foos.Where(m => m.Bar == "bar");
// Add a new Foo
db.Foos.Add(new Foo { Bar = "bar" });
So on and so forth. Other ORMS like NHibernate have slight different setups and API, but they all basically behave the same and don't require that you worry about generating SQL.

How can I retrieve the query definition (SQL text) of an Access query and store back a changed definition

I have a requirement where I need to read queries from Access DB in c# and check if the access db query has any keyword like "KEY" if it has keywords I need to enclose that in square brackets"[]".just like how it is done in SQL.
Could someone suggest me how to do that?
You can retrieve the query text like this:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\...\myDB.mdb";
using (var conn = new OleDbConnection(connString )) {
conn.Open();
string[] restrictions = new string[] { null, null, "myQuery" };
DataTable schema = conn.GetSchema("Views", restrictions);
if (schema.Rows.Count > 0) {
DataRow row = schema.Rows[0];
string queryText = (string)row["VIEW_DEFINITION"];
Console.WriteLine(queryText);
}
}
If you drop the restrictions argument with the query name, conn.GetSchema("Views") returns one row for each query. If you query conn.GetSchema("Procedures") other types of queries like insert, update and DDL statements that are not considered as queries are returned in row["PROCEDURE_DEFINITION"].
View (query) names are returned in row["TABLE_NAME"] and procedure names in row["PROCEDURE_NAME"].
And you can update the query like this:
using (var conn = new OleDbConnection(connString)) {
conn.Open();
var cmd = new OleDbCommand("DROP PROCEDURE myQuery", conn);
cmd.ExecuteNonQuery();
cmd = new OleDbCommand("CREATE PROCEDURE myQuery AS SELECT * FROM myTable", conn);
cmd.ExecuteNonQuery();
}
Strangely enough the OleDb CREATE DDL (Data Definition Language) designates the queries as 'procedures' but the schema table returns a 'VIEW_DEFINITION' and the query name is returned in the column 'TABLE_NAME'. SELECT queries must be retrieved as "Views", other types of queries as "Procedures"; however, both types are created as PROCEDUREs.
While I was testing the answer that #Olivier Jacot-Descombes provided, I was not able to retreive all the queries text representation. Therefore I applied some other method where you open the existing Ms Access database instance and read the queries that are stored in it.
Here is the class I used:
public class MsAccess
{
private Microsoft.Office.Interop.Access._Application _oAccess;
public MsAccess(string path)
{
_oAccess = (Microsoft.Office.Interop.Access._Application)System.Runtime.InteropServices.Marshal.BindToMoniker(path);
}
public string ReturnSqlQueryText(string queryName)
{
string queryDef = null;
var qdefs = _oAccess.CurrentDb().QueryDefs;
foreach (QueryDef qdef in qdefs)
{
if(qdef.Name.Equals(queryName))
queryDef = qdef.SQL;
}
return queryDef;
}
}
Using this code might require you adding using Microsoft.Office.Interop.Access.Dao and Microsoft.Office.Interop.Access both (15.0.0.0) where you can find them under Extension on the reference menu

C# SqlParameters Short Hand

I'm taking data that is in a List of Record objects and putting their contents in to a database:
// Processes a Record and adds it to the database
public bool addRecord(SqlConnection db, List<Record> recordsToAdd)
{
using (SqlCommand command = db.CreateCommand())
{
foreach (Record record in recordsToAdd)
{
// Set the query command text
command.CommandText = #"INSERT INTO SMDGROUP_STPRODMASTER (PRODCODE, TOTFREE, TOTPHYS, ITEMTYPE, PRODESC) VALUES ('#PRODCODE', '#TOTFREE', '#TOTPHYS', '#ITEMTYPE', '#PRODESC')";
SqlParameter param1 = new SqlParameter("#CURSTAT", record.curstat);
SqlParameter param2 = new SqlParameter("#ITEMDESC", record.itemdesc);
SqlParameter param3 = new SqlParameter("#PRODCODE", record.prodcode);
SqlParameter param4 = new SqlParameter("#TOTFREE", record.totfree);
SqlParameter param5 = new SqlParameter("#TOTPHYS", record.totphys);
SqlParameter param6 = new SqlParameter("#ITEMTYPE", record.itemtype);
SqlParameter param7 = new SqlParameter("#PRODESC", record.proddesc);
command.Parameters.Add(param1);
command.Parameters.Add(param2);
command.Parameters.Add(param3);
command.Parameters.Add(param4);
command.Parameters.Add(param5);
command.Parameters.Add(param6);
command.Parameters.Add(param7);
// Execute the query
command.ExecuteNonQuery();
}
return true;
}
}
Here's my Record class:
class Record
{
public string curstat { get; set; }
public string itemtype { get; set; }
public string itemdesc { get; set; }
public string prodcode { get; set; }
public string proddesc { get; set; }
public string totfree { get; set; }
public string totphys { get; set; }
}
Just from looking at the code, I've got a feeling that there is a shorter way of achieving this.
But secondly, I'm not even sure if I've done it correctly that the #PARAMETER values are being replaced.
If I view the contents of command, it still shows the query string with the # parameters.
Also, I'm getting this error on command.ExecuteNonQuery():
String or binary data would be truncated.
The statement has been terminated.
So, my questions are:
Is there a shorter way to set and add multiple parameters to the query?
What could be causing the error?
You have a bigger constructor:
command.Parameters.Add(
"#CategoryName", SqlDbType.VarChar, 80).Value = "toasters";
Using the method AddWithValue will make the code a little bit shorter:
command.Parameters.AddWithValue("#CURSTAT", record.curstat);
//...
I do it a bit differntly.
I have both a extension method and a static method to create SqlParameters.
public static SqlParameter ToParam(this object v,string name){
return new SqlParameter(name,v);
}
Then I do something like this:
var p = new List<SqlParameter>();
p.Add(record.curstat.ToParam("#curstat"));
p.Add(record.itemdesc.ToParam("#itemdesc"));
//etc...
command.Parameters.AddRange(p.ToList());
The String or binary data would be truncated. most likely means your putting too many characters into one of your VARCHAR fields. I.e., if your column PRODDESC is a VARCHAR(50), and the string you're trying to insert is 70 characters, you will see that error.
Others have addressed alternative ways of doing the parameters so you can reduce the lines of code.
For a shorter syntax, you can use AddRange method of the SqlParameterCollection class. It means:
command.Parameters.AddRange(new [] {
new SqlParameter(...),
new SqlParameter(...),
new SqlParameter(...) });
The error you're getting indicates that a string value doesn't fit in the table column or parameter, and is being truncated. You should check the length of the column in comparison to the data being inserted, or specify the length of parameters using another overload of the SqlParameter constructor.
If you wanted to use the following class:
Class MyParam
{
public string name {get;set;}
public object value {get;set;}
}
then you could have a List called myParams and do:
foreach(var p in myParams) command.Parameters.AddWithValue(p.name, p.value);
You obviously have to link the parameters and values somehow and there's no way around that. But if you do it in a class like this then the code that actually does the action is only one line long.
I think the message
String or binary data would be truncated.
The statement has been terminated.
comes from an error in your Command Text: in the SQL Query the parameters, even if they are strings, do not need to be quoted.
Replace the command with this
command.CommandText = #"INSERT INTO SMDGROUP_STPRODMASTER
(PRODCODE, TOTFREE, TOTPHYS, ITEMTYPE, PRODESC)
VALUES (#PRODCODE, #TOTFREE, #TOTPHYS, #ITEMTYPE, #PRODESC)";
To shorten the code i think you could add somewhere (for example in your record class or in an helper class) a method that creates an array of parameter from a record object and then call the AddRange function. It should keeps this function cleaner and you could use it also in other part of you code.
In regards to the error, it's a truncation problem i.e. the length of your parameter is longer than what your column can hold. To resolve this, be more specific when passing your parameters e.g. new SqlParameter("#MyParameter", SqlDbType.VarChar, 30).
Personally I don't think their is anything wrong with how your currently adding the parameters it's readable and does the job. If, however, you want to reduce the amont of lines of code in your function you could either go with what #Royi has suggested or simply package up the parameter adding into another method.
This worked for me:
comando.Parameters.Add(
"#EmailAddress", SqlDbType.VarChar).Value = EmailAddress;

Categories

Resources