Original source: Http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model
EntityFramework (EF) supports the code first development approach. Three development methodologies Database first, model first, and code first are preferred. Code first, the class of the model object is created, and the corresponding database can be generated automatically through the ORM tool, which is a very fast and clean development process.
First, add the model
1. Create a new default ASP. NET MVC 4 Web site with the name Mvcmovie.
2. Right-click the Models folder and add Class Movie.cs
Public classMovie { Public intID {Get;Set; } Public stringTitle {Get;Set; } PublicDateTime ReleaseDate {Get;Set; } Public stringGenre {Get;Set; } Public decimalPrice {Get;Set; }}
We will use the movie class to represent the movies information in the database, and each property in the movie class corresponds to a field in the database table, and the instance of the movie object will correspond to a row of the database table.
3. Add the Moviedbcontext class in the Models folder
Public class Moviedbcontext:dbcontext { publicgetset;}}
The Moviedbcontext class represents the EF Movie Database context, which handles reading and writing updates to the movie class instance in the database. The DbContext class is provided by EF and requires a reference statement
using System.Data.Entity;
4. Create a database connection
Open the Web. config file under the application root directory, not the one in the View folder. In the <connectionStrings> element, add the connection string.
<add name="moviedbcontext" connectionstring="Data source= (LocalDB) \v11.0; attachdbfilename=| datadirectory|\movies.mdf;integrated security=true" providername="System.Data.SqlClient
Second, add the controller
1. Right-click the Controllers folder to create the movies controller.
If the option does not appear, compile the application first.
Vs created the Movies folder under the MoviesController.cs, Views folder (contains Create.cshtml, delete.cshtml, details.cshtml, edit.cshtml, index.cshtml).
ASP. NET MVC 4 automatically generates CRUD (create, read, update, delete) methods and views, called Scaffolding Code (scaffolding), which can now be used for CRUD operations.
2. Running the program
Try to manipulate the edit, details, and delete functions.
3. Learn about auto-generated code
Public class moviescontroller:controller{ privatenew moviedbcontext (); // // GET:/movies/ Public actionresult Index () { return View (db. Movies.tolist ()); }
Walkthrough 2-4:codefirst Example of "movie website production"