I'm re-writing the inline SQL in my repository class to use stored procedures instead (security requirement). After using Fluent NHibernate and Linq2Sql in the past I'm finding it to be extremely unwieldy and inelegant.
EDIT: To clarify, I'm not looking for an ORM solution that works with stored procs. I just want some advice on a nice way to write the code below.
Are there any strategies for making this sort of code as elegant as possible?
string commandText = "dbo.Save";
using (SqlConnection sql = new SqlConnection(_connString.ConnectionString))
using (SqlCommand cmd = sql.CreateCommand())
{
cmd.CommandText = commandText;
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter idParam = new SqlParameter("identity", item.Identity);
idParam.Direction = ParameterDirection.Input;
SqlParameter nameParam = new SqlParameter("name", item.Name);
nameParam.Direction = ParameterDirection.Input;
SqlParameter descParam = new SqlParameter("desc", item.Description);
descParam.Direction = ParameterDirection.Input;
SqlParameter titleParam = new SqlParameter("title", item.)
descParam.Direction = ParameterDirection.Input;
//SNIP More parameters
cmd.Parameters.Add(idParam);
cmd.Parameters.Add(descParam);
cmd.Parameters.Add(titleParam);
//SNIP etc
sql.Open();
cmd.ExecuteNonQuery();
//Get out parameters
}
return item;
Stored procedures have been falling out of favour for several years now. The preferred approach these days for accessing a relational database is via an O/R mapper such as NHibernate or Entity Framework. Stored procedures require much more work to develop and maintain.
In Object Explorer, connect to an instance of the SQL Server Database Engine, expand that instance, and then expand Databases. Expand the database that you want, expand Programmability, and then expand Stored Procedures. Right-click the user-defined stored procedure that you want and select Execute Stored Procedure.
Within our internal applications we generally use the SqlHelper class which can be found at the following link (download and description): http://www.microsoft.com/downloads/details.aspx?familyid=f63d1f0a-9877-4a7b-88ec-0426b48df275&displaylang=en
Essentially the SqlHelper class takes away some of the need to declare connection objects, commands etc and allows you to call methods to return objects such as DataSet
You might then use SqlHelper as such:
public static int UpdateItem(int parameter1, int parameter2, string parameter3)
{
SqlParameter[] arParam = new SqlParameter[3];
arParam[0] = new SqlParameter("@Parameter1", lotId);
arParam[1] = new SqlParameter("@Parameter2", saleId);
arParam[2] = new SqlParameter("@Parameter3", lotNumber);
return int.Parse(SqlHelper.ExecuteScalar(connString, CommandType.StoredProcedure, "spName", arParam).ToString(), CultureInfo.InvariantCulture);
}
Hope this helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With