简体   繁体   中英

How do I simplify this verbose ADO.NET Database Code

Trivial question - I'm inexperienced with C# .

I have the following code to call a multi-parameter SQL-Server stored procedure. It works and it is nice and explicit ie easy to read what is happening but it's very verbose.

Is there a standard shorter version of the following?

using(var conn = new SqlConnection(this.connString))
using(var comm = new SqlCommand(DatabaseLayer.procSendEmail,conn))
{
  comm.CommandType = CommandType.StoredProcedure;

  SqlParameter pmIsTemplate = new SqlParameter("@IsTemplate",SqlDbType.TinyInt);
  SqlParameter pmDateInsertKey = new SqlParameter("@DateInsertKey",SqlDbType.Int);
  SqlParameter pmEmailTO = new SqlParameter("@EmailTO",SqlDbType.NVarChar,1000);
  SqlParameter pmEmailBody = new SqlParameter("@EmailBody",SqlDbType.NVarChar,-1);
  SqlParameter pmEmailImportance = new SqlParameter("@EmailImportance",SqlDbType.TinyInt);
  SqlParameter pmEmailSubject = new SqlParameter("@EmailSubject",SqlDbType.NVarChar,1000);
  SqlParameter pmSuccess = new SqlParameter("@Success",SqlDbType.Bit);

  pmIsTemplate.Direction        = ParameterDirection.Input;
  pmDateInsertKey.Direction     = ParameterDirection.Input;
  pmEmailTO.Direction           = ParameterDirection.Input;
  pmEmailBody.Direction         = ParameterDirection.Input;
  pmEmailImportance.Direction   = ParameterDirection.Input;
  pmEmailSubject.Direction      = ParameterDirection.Input;
  pmSuccess.Direction           = ParameterDirection.Output;

  comm.Parameters.Add(pmIsTemplate);
  comm.Parameters.Add(pmDateInsertKey);
  comm.Parameters.Add(pmEmailTO);
  comm.Parameters.Add(pmEmailBody);
  comm.Parameters.Add(pmEmailImportance);
  comm.Parameters.Add(pmEmailSubject);
  comm.Parameters.Add(pmSuccess);

  ...
  ...

Maybe doing something like this:

using (var conn = new SqlConnection(this.connString))
{
    using (var comm = new SqlCommand(DatabaseLayer.procSendEmail, conn) { CommandType = CommandType.StoredProcedure })
    {
        comm.Parameters.Add(new SqlParameter("@IsTemplate", SqlDbType.TinyInt));
        comm.Parameters.Add(new SqlParameter("@DateInsertKey", SqlDbType.Int));
        comm.Parameters.Add(new SqlParameter("@EmailTO", SqlDbType.NVarChar, 1000));
        comm.Parameters.Add(new SqlParameter("@EmailBody", SqlDbType.NVarChar, -1));
        comm.Parameters.Add(new SqlParameter("@EmailImportance", SqlDbType.TinyInt));
        comm.Parameters.Add(new SqlParameter("@EmailSubject", SqlDbType.NVarChar, 1000));
        comm.Parameters.Add(new SqlParameter("@Success", SqlDbType.Bit) { Direction = ParameterDirection.Output });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM