I am a beginner at Asp.net using C# and worked mostly in web forms, most of the time when i do tasks, i repeat the same code over and over at different classes, for example, for inserting data, i have to right insert functionality for every specific form. What i want is to have a generic class where these methods for Insertion, deletion, selection, and updation are defined generically and i only have to instantiate these objects where i submit forms and pass data through parameters to these objects. In Php, we called it a dbClass, i dont know what its called in asp.net, its basically a single class being utilized at every crud operation taking place in the application. It would be highly appreciated if someone can help me. Thanks in advance
2 Answers
I would recommend you using an ORM like Entity Framework and the (Generic) Repository Pattern. I believe that will suit your needs and will help you enforce the DRY principle.
In addition, if you're using ASP.NET Web Forms 4.5 you should take a look at the new Model Binding feature.
1 Comment
Majid Khan Mohmand
Thanks for your answer Meryovi. I followed yours steps and am quite happy learning and implementing EF now, its a piece of cake! Way to easy for CRUD operations! Thanks for the suggestions
namespace Steps
{
public class conn
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
public conn()
{
con.ConnectionString = "Data Source=LCCSERVER;Initial Catalog=steps;User ID=sa;Password=admin123";
cmd.Connection = con;
}
public void openconnection()
//using for eliminating the connection error
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
}
public SqlCommand getcommand
{
get
{
return cmd;
}
}
}
public static class crud
{
static conn c = new conn();
public static string insupdel(string spname, params Object[] values)
{
c.openconnection();
c.getcommand.CommandType = CommandType.StoredProcedure;
c.getcommand.CommandText = spname;
SqlCommandBuilder.DeriveParameters(c.getcommand);
int i = 0, j = 0;
foreach (SqlParameter spram in c.getcommand.Parameters)
{
if (j > 0)
{
spram.Value = values[i];
i++;
}
j++;
}
c.getcommand.ExecuteNonQuery();
return "success";
}
public static DataSet getdata(string spname, params Object[] values)
{
c.openconnection();
c.getcommand.CommandType = CommandType.StoredProcedure;
c.getcommand.CommandText = spname;
SqlCommandBuilder.DeriveParameters(c.getcommand);
int i = 0, j = 0;
foreach (SqlParameter spram in c.getcommand.Parameters)
{
if (j > 0)
{
spram.Value = values[i];
i++;
}
j++;
}
SqlDataAdapter ad = new SqlDataAdapter();
DataSet ds = new DataSet();
ad.SelectCommand = c.getcommand;
ad.Fill(ds);
return ds;
}
}
}