Entity Framework Code First Example in MVC 4.

This example will show you how to create a MVC 4 application using Entity Framework Code First in Visual Studio 2012.

1. Create a new Project MVC 4 Internet template. Name: MVCMovieTraining.

2. In the Models folder add new class. Name: Movie.cs. This class will be the POCO (Plain Old CLR Class) class used by the Entity Framework.

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 string Rating { get; set; }
}

For DataAnnotations decorations, reference:

Using System.ComponentModel.DataAnnotations;

Finished class with decorations added.

using System.ComponentModel.DataAnnotations;

namespace MVCMovingTraining.Models
{
   public class Movie
   {
      public int Id { get; set; }
      [Required(ErrorMessage="Title is a required field.")]
      public string Title { get; set; }
      public DateTime ReleaseDate { get; set; }
      public string Genre { get; set;}
      [Required(ErrorMessage="Price is a required field.")]
      [Range (1, 100, ErrorMessage = "Price must be between 1 and 100.")]
      public Decimal Price { get; set; }
      [StringLength(5)]
      public string Rating { get; set; }
   }
}

3. In Web.config add the connection string to the database like this:

  <connectionStrings>
    <add name="MovieDBContext" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCMovieTraining;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  </connectionStrings>

Change the SERVERNAME with the SQL Server’s name you will use. This example uses a SQLExpress database you can use other versions but you need to change it here accordingly.

4. Add a class. Name: MovieDBContext. Dont’ forget to add a reference to System.Data.Entity.

using System.Data.Entity;

public class MovieDBContext : DbContext
{
   public DbSet<Movie> { get; set; }
}

You can add an initializer and seed the database:

    public class MovieInitializer : DropCreateDatabaseIfModelChanges<MovieDbContext>
    {
        protected override void Seed(MovieDbContext context)
        {
            var movies = new List<Movie>{
                new Movie {
                    Title="When Harry Met Sally",
                    ReleaseDate=DateTime.Parse("1989-1-1"),
                    Genre="Romantic Comedy",
                    Rating="G",
                    Price=7.99M
                },
                new Movie {
                    Title = "Hard to Die",
                    ReleaseDate= DateTime.Parse("2000-1-1"),
                    Genre="Action",
                    Rating = "PG14",
                    Price = 10M
                },
            };
            movies.ForEach(d=> context.Movies.Add(d));
        }
    }

Remember that you don’t need to call context.SaveChanges(); the base class takes care.

In Global.asax you need to call the initializer from the Application_Start():

// add these 2 references
using System.Data.Entity;
using MVCMovieTraining.Models;
...
protected void Application_Start();
{
   Database.SetInitializer<MovieDbContext>(new MovieInitializer());
   ...
}
...

When the application is in production remember to not recreate the database if the model changes. Like this:

Database.SetInitializer<MovieDbContext>(null);

5. Add a Controller name: TrainingMovieController,

Template: Controller with read/write actions and views, using Entity Framework.

Model class: Movie (MvcMovieTraining.Models)

Data context class: MovieDBContext (MvcMovieTraining.Models)

Notes:

  1. If you can’t see the class Movie in the list then Build the Project first.
  2. If you want the controller to be the start-up controller in RouteConfig.cs comment the default route and add this line:
    defaults: new { controller = "TrainingMovieController", action = "Index", id = UrlParameter.Optional }
  3. Or if you want to add a link to your controller in Views\Shared\_Layout.cshtml add the “Training Movie” ActionLink after “Contact”:
    <li>@HTML.ActionLink("Training Movie", "Index", "TrainingMovie")<li>

6. Run the Project. The first time the Entity Framework Code First will create the database then the table.

Note: The seed rows will not appear at first because we use DropCreateDatabaseIfModelChanges so it will only seed if the model changes, our model in this case is the class Movie.cs

Note 2: In the MovieDbContext.cs if you omit the type you’ll get an error. Read the following:

public DbSet Movies { get; set;}
//generates the error: cannot create controller with entity framework unable to retrieve metadata
public DbSet<Movie> Movies { get; set; }
Advertisements
This entry was posted in CSharp, Entity Framework, MVC, Visual Studio 2012 and tagged , , , , , , , , . Bookmark the permalink.

One Response to Entity Framework Code First Example in MVC 4.

  1. Pingback: Repository Pattern | pepitosolis

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s