Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

ASP.NET MVC Database

ASP.NET MVC - SQL Database


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

Part 6: Add a database.


Create the database

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

This database required by the tutorial can be created in a few simple steps:

***** If SQL Server Compact Local Database is not in the options, it means SQL Server Compact is not yet installed on your computer. Please install it via the following link:SQL Server Compact

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

**Note:** This tutorial requires you to know some basics about SQL databases. If you want to learn this topic first, please visit our SQL tutorial。


Add a database table

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

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

Create the following columns:

column Type Whether null is allowed
ID int (primary key) No
Title nvarchar(100) No
Director nvarchar(100) No
Date datetime No

Explanation of the columns:

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

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

Director is a text column 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) of the table. To do this, click the column name (ID) and select Primary Key. In the **Column Properties** window, set the Identity property to **True**:

DB Explorer

After you have created the table columns, save the table and name it MovieDBs。

Note:

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


Add database records

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

Double-click App_Data the Movies.sdf files.

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

to 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 updates automatically; you do not need to edit it.


Add a connection string

Add the following element to your Web.config file's element:

connectionString="Data Source=|DataDirectory|Movies.sdf"

providerName="System.Data.SqlServerCe.4.0"/>