"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Getting Started with Entity Framework 6 Database First using MVC 5

by Tom FitzMacken

Using MVC, Entity Framework, and ASP.NET Scaffolding, you can create a web application that provides an interface to an existing database. This tutorial series shows you how to automatically generate code that enables users to display, edit, create, and delete data that resides in a database table. The generated code corresponds to the columns in the database table. In the last part of the series, you will deploy the site and database to Azure.

This part of the series focuses on creating a database and populating it with data.

This series was written with contributions from Tom Dykstra and Rick Anderson. It was improved based on feedback from users in the comments section.

Introduction

This topic shows how to start with an existing database and quickly create a web application that enables users to interact with the data. It uses the Entity Framework 6 and MVC 5 to build the web application. The ASP.NET Scaffolding feature enables you to automatically generate code for displaying, updating, creating and deleting data. Using the publishing tools within Visual Studio, you can easily deploy the site and database to Azure.

This topic addresses the situation where you have a database and want to generate code for a web application based on the fields of that database. This approach is called Database First development. If you do not already have an existing database, you can instead use an approach called Code First development which involves defining data classes and generating the database from the class properties.

For an introductory example of Code First development, see Getting Started with ASP.NET MVC 5. For a more advanced example, see Creating an Entity Framework Data Model for an ASP.NET MVC 4 App.

For guidance on selecting which Entity Framework approach to use, see Entity Framework Development Approaches.

Prerequisites

Visual Studio 2013 or Visual Studio Express 2013 for Web

Set up the database

To mimic the environment of having an existing database, you will first create a database with some pre-filled data, and then create your web application that connects to the database.

This tutorial was developed using LocalDB with either Visual Studio 2013 or Visual Studio Express 2013 for Web. You can use an existing database server instead of LocalDB, but depending on your version of Visual Studio and your type of database, all of the data tools in Visual Studio might not be supported. If the tools are not available for your database, you may need to perform some of the database-specific steps within the management suite for your database.

If you have a problem with the database tools in your version of Visual Studio, make sure you have installed the latest version of the database tools. For information about updating or installing the database tools, see Microsoft SQL Server Data Tools.

Launch Visual Studio and create a SQL Server Database Project. Name the project ContosoUniversityData.

create database project
create database project

You now have an empty database project. You will deploy this database to Azure later in this tutorial, so you’ll need to set Azure SQL Database as the target platform for the project. Setting the target platform does not actually deploy the database; it only means that the database project will verify that the database design is compatible with the target platform. To set the target platform, open the Properties for the project and select Microsoft Azure SQL Database for the target platform.

set target platform
set target platform

You can create the tables needed for this tutorial by adding SQL scripts that define the tables. Right-click your project and add a new item.

add new item
add new item

Add a new table named Student.

add student table
add student table

In the table file, replace the T-SQL command with the following code to create the table.

[!code-sqlMain]

   1:  CREATE TABLE [dbo].[Student] (
   2:      [StudentID]      INT           IDENTITY (1, 1) NOT NULL,
   3:      [LastName]       NVARCHAR (50) NULL,
   4:      [FirstName]      NVARCHAR (50) NULL,
   5:      [EnrollmentDate] DATETIME      NULL,
   6:      PRIMARY KEY CLUSTERED ([StudentID] ASC)
   7:  )

Notice that the design window automatically synchronizes with the code. You can work with either the code or designer.

show code and design
show code and design

Add another table. This time name it Course and use the following T-SQL command.

[!code-sqlMain]

   1:  CREATE TABLE [dbo].[Course] (
   2:      [CourseID] INT           IDENTITY (1, 1) NOT NULL,
   3:      [Title]    NVARCHAR (50) NULL,
   4:      [Credits]  INT           NULL,
   5:      PRIMARY KEY CLUSTERED ([CourseID] ASC)
   6:  )

And, repeat one more time to create a table named Enrollment.

[!code-sqlMain]

   1:  CREATE TABLE [dbo].[Enrollment] (
   2:      [EnrollmentID] INT IDENTITY (1, 1) NOT NULL,
   3:      [Grade]        DECIMAL(3, 2) NULL,
   4:      [CourseID]     INT NOT NULL,
   5:      [StudentID]    INT NOT NULL,
   6:      PRIMARY KEY CLUSTERED ([EnrollmentID] ASC),
   7:      CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID] FOREIGN KEY ([CourseID]) 
   8:          REFERENCES [dbo].[Course] ([CourseID]) ON DELETE CASCADE,
   9:      CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID] FOREIGN KEY ([StudentID]) 
  10:          REFERENCES [dbo].[Student] ([StudentID]) ON DELETE CASCADE
  11:  )

You can populate your database with data through a script that is run after the database is deployed. Add a Post-Deployment Script to the project. You can use the default name.

add post-deployment script
add post-deployment script

Add the following T-SQL code to the post-deployment script. This script simply adds data to the database when no matching record is found. It does not overwrite or delete any data you may have entered into the database.

[!code-sqlMain]

   1:  MERGE INTO Course AS Target 
   2:  USING (VALUES 
   3:          (1, 'Economics', 3), 
   4:          (2, 'Literature', 3), 
   5:          (3, 'Chemistry', 4)
   6:  ) 
   7:  AS Source (CourseID, Title, Credits) 
   8:  ON Target.CourseID = Source.CourseID 
   9:  WHEN NOT MATCHED BY TARGET THEN 
  10:  INSERT (Title, Credits) 
  11:  VALUES (Title, Credits);
  12:   
  13:  MERGE INTO Student AS Target
  14:  USING (VALUES 
  15:          (1, 'Tibbetts', 'Donnie', '2013-09-01'), 
  16:          (2, 'Guzman', 'Liza', '2012-01-13'), 
  17:  (3, 'Catlett', 'Phil', '2011-09-03')
  18:  )
  19:  AS Source (StudentID, LastName, FirstName, EnrollmentDate)
  20:  ON Target.StudentID = Source.StudentID
  21:  WHEN NOT MATCHED BY TARGET THEN
  22:  INSERT (LastName, FirstName, EnrollmentDate)
  23:  VALUES (LastName, FirstName, EnrollmentDate);
  24:   
  25:  MERGE INTO Enrollment AS Target
  26:  USING (VALUES 
  27:  (1, 2.00, 1, 1),
  28:  (2, 3.50, 1, 2),
  29:  (3, 4.00, 2, 3),
  30:  (4, 1.80, 2, 1),
  31:  (5, 3.20, 3, 1),
  32:  (6, 4.00, 3, 2)
  33:  )
  34:  AS Source (EnrollmentID, Grade, CourseID, StudentID)
  35:  ON Target.EnrollmentID = Source.EnrollmentID
  36:  WHEN NOT MATCHED BY TARGET THEN
  37:  INSERT (Grade, CourseID, StudentID)
  38:  VALUES (Grade, CourseID, StudentID);

It is important to note that the post-deployment script is run every time you deploy your database project. Therefore, you need to carefully consider your requirements when writing this script. In some cases, you may wish to start over from a known set of data every time the project is deployed. In other cases, you may not want to alter the existing data in any way. Based on your requirements, you can decide whether you need a post-deployment script or what you need to include in the script. For more information about populating your database with a post-deployment script, see Including Data in a SQL Server Database Project.

You now have 4 SQL script files but no actual tables. You are ready to deploy your database project to localdb. In Visual Studio, click the Start button (or F5) to build and deploy your database project. Check the Output tab to verify that the build and deployment succeeded.

show output
show output

To see that the new database has been created, open SQL Server Object Explorer and look for the name of the project in the correct local database server (in this case (localdb)12).

show new database
show new database

To see that the tables are populated with data, right-click a table, and select View Data.

show table data
show table data

An editable view of the table data is displayed.

show table data results
show table data results

Your database is now set up and populated with data. In the next tutorial, you will create a web application for the database.

Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/getting-started/database-first-development/setting-up-database.htm
< THANKS ME>