Easy Tutorial
❮ Prop Webcontrol Bulletedlist Firstbulletnumber Prop Webcontrol Calendar Selectionmode ❯

ASP.NET MVC - SQL Database


To learn ASP.NET MVC, we will build an Internet application.

Part 6: Adding a Database.


Creating a Database

Visual Web Developer comes with a free SQL database called SQL Server Compact.

This database required for the tutorial can be created with a few simple steps:

* If the SQL Server Compact Local Database is not in the options, it means you haven't installed SQL Server Compact on your computer. Please install it through the following link: SQL Server Compact

Visual Web Developer will automatically create the database in the App_Data folder.

Note: For this tutorial, you need to have some basic knowledge about SQL databases. If you want to learn this topic first, please visit our SQL Tutorial.


Adding a Database Table

Double-click the Movies.sdf file in the App_Data folder to open the Database Explorer window.

To create a new table in the database, right-click the Tables folder and select Create Table.

Create the following columns:

Column Type Allow Null
ID int (primary key) No
Title nvarchar(100) No
Director nvarchar(100) No
Date datetime No

Explanation of columns:

ID is an integer (all numbers) used to identify each record in the table.

Title is a text column with a length of 100 characters, used to store the movie's name.

Director is a text column with a length of 100 characters, used to store the director's name.

Date is a date column used to store the movie's release date.

After creating the above columns, you must set the ID column as the primary key (record identifier). To do this, click the column name (ID) and select Primary Key. In the Column Properties window, set the Identity property to True.

When you have created the table columns, save the table and name it MovieDBs.

Note:

We deliberately named the table "MovieDBs" (ending with an 's'). In the next chapter, you will see the "MovieDB" used for the data model. This may seem a bit strange, but this naming convention ensures that the controller connects to the database table, and you must use it.


Adding Database Records

You can use Visual Web Developer to add some test records to the movie database.

Double-click the Movies.sdf file in the App_Data folder.

Right-click the MovieDBs table in the Database Explorer window and select Show Table Data.

Add some records:

ID Title Director Date
1 Psycho Alfred Hitchcock 01.01.1960
2 La Dolce Vita Federico Fellini 01.01.1960

Note: The ID column will update automatically, you don't need to edit it.


Adding a Connection String

Add the following element to the <connectionStrings> element in your Web.config file:

❮ Prop Webcontrol Bulletedlist Firstbulletnumber Prop Webcontrol Calendar Selectionmode ❯