Click here to Skip to main content
15,886,258 members
Articles / Web Development / HTML
Tip/Trick

ASP.NET MVC 5 – Entity Framework 6, CRUD Operations on Visual Studio 2015

Rate me:
Please Sign up or sign in to vote.
3.43/5 (3 votes)
7 Nov 2015CPOL1 min read 37.9K   11   3
ASP.NET MVC 5 – Entity Framework 6, CRUD Operations on Visual Studio 2015

This demo focuses on using ASP.NET Scaffolding to generate the controllers and views.

STEP 1 - Create a New Project on Visual Studio 2015

  • Open Visual Studio
  • Create a new ASP.NET Web Application Project
  • Give a name to the project (in this case, I call him MVC5)
  • Select Template MVC

Image 1

STEP 2 - Create class Movies

Add a new class to the project (this class represents a table, and the properties the columns of that table).

Give a name to that class (in my sample, I call him MoviesModel).

On the class, create the following code:

C#
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Dynamic;
using System.Linq;
using System.Web;

namespace MVC5.Models
{
    public class Email
    {
        public int ID { get; set; }
        public string To { get; set; }
        public string Subject { get; set; }
        public string Message { get; set; }
    }

    public class EmailDBContext : DbContext
    {
        public DbSet<email> Emails { get; set; }
    }
}

Put the class inside the Models folders, just to organize your code.

Image 2

STEP 3 - Create a controller with views using Entity Framework

Add new Scaffolded to the project (new item existent on MVC5):

Image 3

Choose option MVC5 Controller with views using Entity Framework:

Image 4

Click Add

If you receive an error, it may be because you did not build the project in the previous section. If so, try building the project, and then add the scaffolded item again.

Image 5

After the code generation process is complete, you will see a new controller and views in your project.

STEP 4 - Controller and Views Generation

a. The Controller was automatically created with CRUD operations

C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace MVC5.Models
{
    public class MoviesController : Controller
    {
        private MovieDBContext db = new MovieDBContext();

        // GET: Movies
        public async Task<actionresult> Index()
        {
            return View(await db.Movies.ToListAsync());
        }

        // GET: Movies/Details/5
        public async Task<actionresult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = await db.Movies.FindAsync(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // GET: Movies/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Movies/Create
        // To protect from overposting attacks, 
        // please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<actionresult> Create([Bind(Include = 
        	"ID,Title,ReleaseDate,Genre,Price")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(movie);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(movie);
        }

        // GET: Movies/Edit/5
        public async Task<actionresult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = await db.Movies.FindAsync(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // POST: Movies/Edit/5
        // To protect from overposting attacks, 
        // please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<actionresult> 
        Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Entry(movie).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(movie);
        }

        // GET: Movies/Delete/5
        public async Task<actionresult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Movie movie = await db.Movies.FindAsync(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        // POST: Movies/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<actionresult> DeleteConfirmed(int id)
        {
            Movie movie = await db.Movies.FindAsync(id);
            db.Movies.Remove(movie);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

b. The Views were automatically created

Image 6

Run the application:

Image 7

Image 8

MVC5 Resources

Some good online resources about MVC5:

ASP.NET MVC5: The official Microsoft .NET WebSite http://www.asp.net/mvc/tutorials/mvc-5 Image 9

For more examples, follow my blog at http://joaoeduardosousa.wordpress.com/ Image 10

Check My Other Source Code

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Devscope
Portugal Portugal
I am João Sousa, and since i finish my degree I’m working in software development using Microsoft technologies.

I was awarded

Microsoft Most Valuable Professional (MVP) 2015 – .Net

My profissional profile:

Azure Developer
.NET Developer

My Certifications:

MCTS - .NET Framework - Application Development Foundation
MCTS - .NET Framework 2.0 - Windows-based Client Development
MCTS - .NET Framework 3.5 ADO.NET Applications
MCTS - .NET Framework 3.5 ASP.NET Applications
MCSD - Programming in HTML5 with JavaScript and CSS3
MCSD - Developing ASP.NET MVC 4 Web Applications
MCSD - Developing Windows Azure and Web Services
MCSA Office 365 - Managing Office 365 Identities and Requirements
MCSA Office 365 - Enabling Office 365 Services
MCSD - Implementing Microsoft Azure Infrastructure Solutions

Comments and Discussions

 
Questionnice article,but.... Pin
Mekki Ahmedi10-Nov-15 4:48
Mekki Ahmedi10-Nov-15 4:48 
but you created an Email class,and inside your code you are using a Movie class!
To be a good programmer, you must be a good thieve!

Questioncopy past code wrong Pin
fredvr9-Nov-15 1:50
fredvr9-Nov-15 1:50 
QuestionGood Work Pin
Sajini Sadanand8-Nov-15 22:04
professionalSajini Sadanand8-Nov-15 22:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.