TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

ASP.Net MVC Entity Framework

ASP.Net MVC Entity Framework with asp.net tutorial, asp.net introduction, features, project, example, server controls, labels, textbox, button, hyperlink, radiobutton, calender, checkbox, fileupload, events handling, authentication, webforms model binding, html server control, compare validdator, range validator, validation summary, mvc introduction, mvc project, view, validation, entity framework, authentication etc.

<< Back to ASP

ASP.NET MVC Entity Framework

It is a data access framework which used to create and test data in the visual studio. It is part of .NET Framework and Visual Studio. The latest package is shipped as Entity Framework NuGet Package. The latest version is Entity Framework 6.0.

We are using it in our ASP.NET MVC application. First, we will create a project then adding models to it.

This example required the following tools and technologies:

  • Visual Studio 2017
  • .NET 4.5
  • Entity Framework 6.0
  1. Create a MVC Project
  2. Select file menu from menu bar and select new project.

    ASP Framework 1

    Provide name to the project and hit ok.

    ASP Framework 2

    Select template for the project and click ok.

    ASP Framework 3

    After clicking ok, visual studio creates a project that has following structure. In our case project structure looks like this:

    ASP Framework 4

    Now, create a model for table in the database. Right click on the Models folder and add new class by setting name as Student.cs. Modify this class with the following code.


    Model

    // Student.cs

    using System;
    namespace MvcEntityDemo.Models
    {
        public class Student
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
            public string Course { get; set; }
            public string Contact { get; set; }
        }
    }
    

    Create a database context class that is used to coordinate with Entity Framework for a given data model. Place this class in Models folder. Right click on the Models folder and add a class. Provide a name RecordContext.cs to the class. Modify your class with the following code.

    // RecordContext.cs

    using MvcEntityDemo.Models;
    using System.Data.Entity;
    using System.Data.Entity.ModelConfiguration.Conventions;
    namespace MvcEntityDemo.Models
    {
        public class RecordContext : DbContext
        {
            public RecordContext() : base("RecordContext")
            {
            }
            public DbSet<Student> Students { get; set; }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            }
        }
    }
    

Create migration

To create migration, open Package Manager Console by going through view->other windows->Package Manager Console . In Package Manager Console run the following command.

enable-migrations -ContextTypeName MvcEntityDemo.Models.RecordContext

We are executing this command in the following screenshot.

ASP Framework 5

After executing this command, framework creates a Migration folder in the project and a Configuration.cs file.

We are updating this file with the following code.

// Configuration.cs

namespace MvcEntityDemo.Migrations
{
    using MvcEntityDemo.Models;
    using System.Collections.Generic;
    using System.Data.Entity.Migrations;
    internal sealed class Configuration : DbMigrationsConfiguration<MvcEntityDemo.Models.RecordContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
        protected override void Seed(MvcEntityDemo.Models.RecordContext context)
        {
            var students = new List<Student>
            {
            new Student{Name="Mohan",Email="Samuai@example.com",Course="Java Technology", Contact="+25-258628"},
            new Student{Name="Rohan",Email="Sam@example.com",Course=".NET Technology", Contact="+25-258694"},
            new Student{Name="John",Email="Max@example.com",Course="Java Technology", Contact="+25-258999"},
            new Student{Name="Saba",Email="saba@example.com",Course="Linux Administration", Contact="+25-258111"},
            };
            students.ForEach(s => context.Students.Add(s));
            context.SaveChanges();
        }

        }
    }
}

Save this file and run both the following commands in Package Manager Console.

PM> add-migration initial 

After it, run this also

PM> update-database.
ASP Framework 6

This command will create initials for the project inside migration folder.

Create scaffolding to display data on the web page.

ASP Framework 7

Select and add scaffold.

ASP Framework 8

Add controller and provide details to create view as well.

ASP Framework 9

Controller

A new StudentsController has added that contains some auto generated code as given below.

// StudentsController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MvcEntityDemo.Models;
namespace MvcEntityDemo.Controllers
{
    public class StudentsController : Controller
    {
        private RecordContext db = new RecordContext();
        // GET: Students
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }

        // GET: Students/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
        // GET: Students/Create
        public ActionResult Create()
        {
            return View();
        }
        // POST: Students/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Name,Email,Course,Contact")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }
        // GET: Students/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
        // POST: Students/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Name,Email,Course,Contact")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }
        // GET: Students/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
        // POST: Students/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

A Student folder created inside the View folder. This folder contains some auto generated files like Index, Create, Delete etc. The index file contains the following code.

// Index.cshtml

@model IEnumerable<MvcEntityDemo.Models.Student>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Course)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Contact)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Course)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Contact)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}
</table>

Press Ctrl+F5 to run this file then this will produce the following output.

ASP Framework 10




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf