Document directory
- 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 calledCode-first. Code-first allows you to create model object by writing simple classes (also knownPoco, 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 toMvcMovie
Project.
FromToolsMenu, selectLibrary Package ManagerAnd thenAdd library package reference.
TheAdd library package referenceDialog box appears.
By default,AllIs selected in the left pane. Because no packages are installed, the center pane showsNo items found. ClickOnlineIn 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 selectEfcodefirstPackage and clickInstallButton.
After the package instils, clickClose. The installation process downloaded the efcodefirst library and added it toMvcMovie
Project. The efcodefirst Library is contained inEntityframeworkAssembly.
Adding a code-first poco class
InSolution Explorer, Right clickModelsFolder, selectAdd, And then selectClass.
Name the class "movie ".
Add the following code to createMovie
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 followingMovieDBContext
Class:
public class MovieDBContext : DbContext { public DbSet<Movie> Movies { get; set; } }
TheMovieDBContext
Class represents the Entity Framework Movie Database context.MovieDBContext
Class handles fetching, storing, and updatingMovie
Class instances from a database. The completeMovie. CSFile 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 wocould create a database first, then write code to connect to the database. however, here we're re using the code-first approach, so we're '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.