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;
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:
Hope this helps 🙂