I’m building my first web app with .net, and it needs to interact with a very large existing database. I have the connection set up, and have made a class that I can call to build select, insert, update and delete queries passing in several parameters.
I can connect by writing the query I want in the button click, but I want to know is this the best solution? It seems hard to debug this way, as it is mixing the database code with other code.
In the past (in other languages) I have created a class which would contain all of the database query strings and parameters which would be called by the rest of the code. That way if something simple like the stored procedure parameters change, the code is all in one place.
When I look for this in .net, I see nothing about doing it this way and I’m keen to learn the best practices.
protected void Button1_Click(object sender, EventArgs e)
{
NameLabel.Text = UserNoTextBox.Text;
string spName = "SP_SelectUser";
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@User_No", UserNoTextBox.Text)
};
DataAccess dbAccess = new DataAccess();
DataTable retVal = dbAccess.ExecuteParamerizedSelectCommand(spName, CommandType.StoredProcedure, parameters);
}
Update: The class I was referring to was the DataAccess class from the following website:
http://www.codeproject.com/Articles/361579/A-Beginners-Tutorial-for-Understanding-ADO-NET
(Class available at http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=361579)
Update: In the end I opted for using MVC 3 with Entity Framework – it’s great!
This is a huge topic, but a very brief view might be as follows:
DataTablemust die (ok, it has a few uses, but in general: it must die); consider using a custom type such as:It should also be noted that many ORM tools will generate these for you from the underlying table structure.
don’t mix UI and data access; separate this code, ideally into separate classes, but at the minimum into separate methods:
use a library such as an ORM (EF, LINQ-to-SQL, LLBLGenPro) or a micro-ORM (dapper, PetaPoco, etc) – for example, here’s that code with dapper:
or with LINQ-to-SQL (EF is very similar):
not everything needs to be a stored procedure; there used to be a huge performance difference between the two – but that is no longer the case. There are valid reasons to use them (very granular security, shared DB with multiple application consumers, a dba who thinks they are a developer), but they also create maintenance problems, especially when deploying changes. In most cases I would not hesitate to use raw (but parameterized) SQL, for example: