using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace ExamManagement.DLL
{
public class SQLDataAccessHelper
{
string connectionString=string.Empty;
public SQLDataAccessHelper()
{
try
{
connectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
}
catch (Exception)
{
//todo error handling mechanism
throw;
}
}
public void ExecuteNonQuery(string commandText,CommandType commandType, params SqlParameter[] commandParameters)
{
using(var connection= new SqlConnection(connectionString))
using (var command = new SqlCommand(commandText, connection))
{
command.CommandType = commandType;
command.Parameters.AddRange(commandParameters);
connection.Open();
command.ExecuteNonQuery();
}
}
public DataSet ExecuteQuery(string commandText,CommandType commandType,params SqlParameter[] parameters)
{
using(var connection=new SqlConnection(connectionString))
using(var command= new SqlCommand(commandText,connection))
{
DataSet ds=new DataSet();
command.CommandType=commandType;
command.Parameters.AddRange(parameters);
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
connection.Close();
return ds;
}
}
}
}
This is helper class I have written to retrieve data and execute CRUD operation on sql server database either using queries or stored procedures.
Currently it is used from DAL classes as follows :
- I create instance of it
- I call method "ExecuteQuery" and it returns DataSet
Details as follows:
namespace ExamManagement.DLL.Implementations
{
public class StudentDAO : IStudentDAO
{
SQLDataAccessHelper sqlHelper;
public StudentDAO()
{
sqlHelper = new SQLDataAccessHelper();
}
public List<Entities.Student> AllStudents()
{
List<Entities.Student> studentsList = new List<Entities.Student>();
SqlParameter[] parameterList = { new SqlParameter("@Id",DBNull.Value),
new SqlParameter("@name",DBNull.Value),
new SqlParameter("@address",DBNull.Value)};
var table = sqlHelper.ExecuteQuery("GetStudents", System.Data.CommandType.StoredProcedure,parameterList).Tables[0];
studentsList = table.AsEnumerable().Select(row => new Entities.Student { Id = row.Field<int>("Id"), Name = row.Field<string>("Name"), Address = row.Field<string>("Address") }).ToList();
return studentsList;
}
I have following questions with regards to it
Helper class should be static class or the methods in it should be static methods?
Connection string is not supplied by class user, instead its is auto calculated from Web.config using ConfigurationManager. Is this approach ok?
I'm creating connection in "Using" statement, so can I ignore calling connection.Close() or its required even then ?
How can I improve it.
Possible to write unit tests for this class?