文章目錄
- Entity Framework Code-First Development
- Using NuGet to Install EFCodeFirst
- Adding a Code-First POCO Class
Entity Framework Code-First Development
The Entity Framework version 4 supports a development paradigm called code-first. Code-first allows you to create model object by writing simple classes (also known as POCO, from "plain-old CLR objects") and have the database created on the fly from your classes. In order to use code-first, you must install the EFCodeFirst library.
Using NuGet to Install EFCodeFirst
In this section, you'll use the NuGet package manager (automatically installed by ASP.NET MVC 3) to add the EFCodeFirst library to the MvcMovie
project.
From the Tools menu, select Library Package Manager and then Add Library Package Reference.
The Add Library Package Reference dialog box appears.
By default, All is selected in the left pane. Because no packages are installed, the center pane shows No items found. Click Online in the left pane.
NuGet queries the server for all available packages.
There are hundreds of packages available. We're interested in the EFCodeFirst package. In the search box, enter "EFCode", and then select the EFCodeFirst package and click the Install button.
After the package installs, click Close. The installation process downloaded the EFCodeFirst library and added it to the MvcMovie
project. The EFCodeFirst library is contained in the EntityFramework assembly.
Adding a Code-First POCO Class
In Solution Explorer, right click the Models folder, select Add, and then select Class.
Name the class "Movie".
Add the following code to create the Movie
class:
public class Movie { public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } }
In the same file, add the following MovieDBContext
class:
public class MovieDBContext : DbContext { public DbSet<Movie> Movies { get; set; } }
The MovieDBContext
class represents the Entity Framework movie database context. The MovieDBContext
class handles fetching, storing, and updating Movie
class instances from a database. The complete Movie.cs file is shown below.
using System; using System.Data.Entity; namespace MvcMovie.Models { public class Movie { public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } } public class MovieDBContext : DbContext { public DbSet<Movie> Movies { get; set; } } }
Our application has not connected to a database yet. In traditional web application development, we would create a database first, then write code to connect to the database. However, here we're using the code-first approach, so we've written our code (models) first. Later in the tutorial when you run the application, the code will create a database and movie table on the fly.