EF Database First with ASP.NET MVC: Creating the Web Application and Data Models
Using MVC, Entity Framework, and ASP.NET Scaffolding, you can quickly create a web application that provides an interface to an existing database. This tutorial series shows you how to automatically generate code for models, views, and controllers that enable 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.
This part of the series focuses on creating the web application, and generating the data models based on your database tables.
Create a new ASP.NET Web Application
Now, you will create the web application. Create a new project in Visual Studio, and select the ASP.NET Web Application template. Name the project ContosoSite.
Click OK.
In the New ASP.NET Project window, select the MVC template and click Create Project.
The project is created with the default files and folders.
Generate the models
You will now create Entity Framework models from the database tables. These models are classes that you will use to work with the data. Each model mirrors a table in the database and contains properties that correspond to the columns in the table.
Right-click the Models folder, and select Add and New Item.
In the Add New Item window, select Data in the left pane and ADO.NET Entity Data Model from the options in the center pane. Name the new model file ContosoModel.edmx.
Click Add.
In the Entity Data Model Wizard, select Generate from database.
Click Next.
Select the data connection you added earlier.
Click Next.
Select Tables to generate models for all three tables.
Click Finish.
If you receive a security warning, select OK to continue running the template.
The models are generated from the database tables, and a diagram is displayed that shows the properties and relationships between the tables.
The Models folder now includes many new files related to the models that were generated from the database.
The ContosoModel.Context.cs file contains a class that derives from the DbContext class, and provides a property for each model class that corresponds to a database table. The Course.cs, Enrollment.cs, and Student.cs files contain the model classes that represent the databases tables. You will use both the context class and the model classes when working with scaffolding.
Before proceeding with this tutorial, build the project. In the next section, you will generate code based on the data models, but that section will not work if the project has not been built.
Comments (0) RSS Feed