ASP.NET Photo Album Part 1 – The Database
This is the first part of the ASP.NET Photo Album tutorial series. This tutorial will walk you through the steps of creating the necessary database to hold our image data with ASP.NET 4.0 and C#.
Adding the Database
To begin creating our photo album, we will need to add a database to our web site that will allow us to store all of the necessary data that is associated with our images. In this tutorial, we will be storing our images as binary data in the database. At this point, I have created a new ASP.NET Empty Web Site. To begin:
- Right click the project in your solution explorer.
- Select add ASP.NET folder.
- Select App_Data.
- Right click the App_Data folder.
- Select add new item…
- Select a SQL Database.
- Name it ‘Database.mdf’.
- Click add.
For this photo album, we will allow the user to associate a date and a message with each image. That being said, we will need that data on top of the data we will need to store the image. This means that we will need to store the following:
- Image ID – This will be the primary key and identity of the table that will serve as the unique identifier for each image.
- Image Binary – The actual binary data of the image.
- Image Size – The size of the image in bytes.
- Image Type – The type of image.
- Image Date – The date associated with the image by the user.
- Image Message – The message associated with the image by the user.
Adding the Table
Now that we have identified what data we need to store, we need to go ahead and add our table. To do this:
- Expand the Database.mdf folder in your server/database explorer.
- Right click the Tables folder.
- Select add new table.
- Add the following columns with their respective types to the table:
Column Name Data Type Allow Nulls? ImgId int No ImgBin image No ImgSize bigint No ImgType nvarchar(50) No ImgDate date Yes ImgMessage nvarchar(1024) Yes
- Right click the ImgId column and select Set Primary Key.
- Change the IsIdentity property of the ImgId column to ‘Yes’.
Adding the ConnectionString
Now that we have our database all setup, all we have left to do is add in a connection string to it so that we can access it in code. To do this, open up the Web.Config file for editing and add in the following code between the
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>