Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVC 3.0 Code First for Beginners

0.00/5 (No votes)
31 Jul 2012 2  
First part to the three part series of articles describing how to create a information system where teachers can manage there students and classes. This tutorial will go in depth on using MVC's Code First approach and touch on using MvcScaffolding in the Nuget Package Console.

Introduction  

For an independent study focused on using MVC 3.0 over the summer, I put together this article to show how great this technology is and the incredible ease of use that can turn you into developing Web-Applications for businesses or personal use in a rapid agile environment. This article will touch on a new method using MVC called the Code First Approach that makes developing apps simple without much hassle. We will also be extending this approach by using an extension called the Nuget Package Console in order to build our Views and Controllers.  

About MVC     

MVC stands for Model-View-Controller which is an architectural pattern that separates your application into three main components,"model, the view, & controller." Here is a great resource that explains this design pattern. It is essential that you look at this resource before continuing on. 

Some great tutorials can be found here that can help understand MVC. If you complete one of these tutorials then you should have no problem following along this tutorial.    

Microsoft just released MVC 4.0 RC that is equipped with new features such as Web API support, Mobile App Features, and enhanced support for asynchronous methods. Read the full features list in the release candidate notes.    

Although the new addition is in its release candidate stages, the new features supported merely let you develop highly sophisticated web-applications from mobile to web in a fluid and easily manner.  

Prerequsities 

To get started you must have the following installed:

1. Visual Studio 2010 

2. MVC 3.0 

3. Service Pack 1

4. Nuget  

5. Source Code for Part 1 *Good to download so you can follow a long easily but not required*

What we will be building  

For this tutorial we will be building a student management system using the Code First Approach. In the student management system teachers can add courses and students. They will be able to manage students in each course and keep notes on different lectures pertaining to different courses. This tutorial will be a 3 part series that will get you to build a student information system allowing teachers to  manage students, lectures, classes, keep notes on lectures and/or students, and keep track of students attendance. It will also notify the teacher if the student is falling behind by missing to many classes. For this article we will be going over the 1st part in the series of articles. The 1st part will create the base layer to get this started. After completing the 1st part, users will be able to add and create classes or students as well as take notes on the students and classes.

This information system can be created with very little code and in a matter of an hour if you are familiar with this approach. Here is a great description about the Code First Approach that you should read before continuing. 

**Parts 2 & 3 will be released when I get a little bit of free time within a couple weeks from the creation date of this article"** 

Part 1  

Step 1 - Create a Project    

1. Open Visual Studio and under the File Menu select create new project.  

2. Select create new MVC 3 Project. 

3. Create an MVC 3 Project that has an internet application template a long with HTML5 semantic markup just like Figure 1. Name your project/solution what ever you would like.    

 

 Figure 1 

Step 2 - Create a Model  

1. In the solution explorer right click on the Model folder and create a new class.  Figure 2 

 Figure 2 

2. Name the class ManagementModel.cs 

Once you create the class, the following code is created inside the class.  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace MvcApplication.Models
{
    public class ManagementModel
    {
    }
}     

3. Change the public class MangementModel to the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace MvcApplication.Models
{
    public class Course
    {
        public int CourseId { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Student> Students { get; set; }
        public virtual ICollection<Lecture> Lectures { get; set; } 
    }
 
    public class Lecture
    {
        public int LectureId { get; set; }
        public string Name { get; set; }
        public DateTime Date { get; set; }
        public string Description { get; set; }
        public string Notes { get; set; }
        public int CourseId { get; set; }
        public virtual Course Course { get; set; }
    }
 
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Notes { get; set; }
        public int CourseId { get; set; }
        public virtual Course Course { get; set; }
    }
}   

From the model we have created, Mvc will automatically create a database in our app-data folder that will store all the data after completing Step 3 which eliminates a lot of tedium work. As you can see the class Courses has one to many relationships with the classes Lectures & Students. To learn more about creating models with different relationships and for a more in depth understanding of what we will be doing in Step 3 click here.

Step 3 - Scaffolding with Nugets Command Line

In order to continue you must ensure you have the latest version of Nuget installed as listed in the prerequisites section of this article. 

Nuget is a great way to manage extensions/packages for your Mvc Project. It makes creating applications such as the one we are extremely easy and face-paced. Here is a good resource if you a new to Nuget that explains installation and various commands you can input into Nugets command line. get started we are going to ensure we have the latest version of entity framework installed. 

1. Open the Nuget Command Console under the Library Package Sub Menu in the Tools Menu.

2. Input into the command line Update-Package EntityFramework as in Figure 3.   

Figure 3 

After updating Entity Framework we will want to install a new package that allows us to easily scaffold our Models into a View as well as Controller. To accomplish this we will be adding an extension called MVC Scaffolding.  Steve Sandersons Blog is a great resource for those considering this approach and more in depth tutorials. Steve Sandersons Blog. 

3. In the Nuget Command Line type the following: Install-Package MvcScaffolding 

4. Then type the following into the Command Line:

Scaffold Controller Course 

This will automatically scaffold a Controller and View from the class Course in our  in the file named ManagementModel.cs.

5. Scaffold a controller for the other three classes (Student & Lecture) in the ManagementModel.cs  by typing the following code: 

Scaffold Controller Student 

Then  

Scaffold Controller Lecture  

6. Run the solution and create a new course by adding the following to your localhosts port number: localhost:yourprojectport#/Courses/Create  

As you can see a form was automatically created that allows us to create a new course.  

7. Create a new course of the desired name you choose. I will create a new course called Systems Analysis and Design.  

After creating a Course you will be redirected to your localhost/Courses view. This view has a grid showing you the Courses that you have created as in Figure 4. It also includes the number of students and lectures that each course has. Currently there are 0 students and 0 lecutres because we have not created any students or lectures. Lets add some students and lectures:

8. Select the Create New under the Course Grid View and add a couple more courses.   

 

 Figure 4  

9. Go to the url localhost/yourprojectport#/Students/Create and create some students by filling out the form. 

10. Go to the url localhost/yourprojectport#/Lectures/Create and create some lectures for each Course.    

You may or may have not noticed that MVC has automatically error trapped our forms to make sure that users input the correct requirements of each field like Figure 5.  


Figure 5 

Step 4 - The Layout View 

1. In the Shared Folder under Views in the Solution explore you notice a file called _Layout.cshtml. This file allows you to create the surrounding layout of your website. The layout will surround each View that is created. Lets create add menu items so Users can easily navigate to the Students/Lectures or Courses View. To do this we will change the add this code under the <nav> tag.

   <li>@Html.ActionLink("Courses", "Index", "Courses")</li>
   <li>@Html.ActionLink("Lectures", "Index", "Lectures")</li>
   <li>@Html.ActionLink("Students", "Index", "Students")</li>   

This is what your Layout View should look like after you make the above changes. 

<pre lang="html"><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
            <nav>
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
 
                     <li>@Html.ActionLink("Courses", "Index", "Courses")</li>
                    <li>@Html.ActionLink("Lectures", "Index", "Lectures")</li>
                     <li>@Html.ActionLink("Students", "Index", "Students")</li>
                </ul>
            </nav>
        </header>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>    

 2. Run the Solution and you've completed Part 1! The final result should look like Figure 6-9

 

Figure 6 


Figure 7 

Figure 8 

Figure 9 

Summary

As you can see it is extremely easy to create a simple application in Mvc 3.0 using the Code First Approach with MvcScaffolding. For Part 2 of this series we will implementing the ability for teachers to take attendance and a notification system that allows teachers to see slacking students who are missing several classes. Part 3 will go over security and will have an in depth look at our Controllers. Check back soon to get those tutorials. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here