DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on • Edited on

ASP.NET MVC 5 Using DBContext Connect Database

Continue! the article previous, today, I'm shared example simple, Using DBContext Connect Database in ASP.NET MVC 5
The article previous, you can see the list below

Install Entity Framework 6.x
Tools->Nuget Package Manager
ASP.NET MVC 5 Using DBContext Connect Database

Entity Framewok: it hepls us to map relationship object in the database used in ADO.NET

Okay, we need create database in App_Data directory, you click right App_Data->New Item
ASP.NET MVC 5 Using DBContext Connect Database - hoanguyenit.com

After then, you open Web.config in project, add the following below code is connect database

<connectionStrings>
    <add name="demoASPEntities" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=demomvc5;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\demomvc5.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Enter fullscreen mode Exit fullscreen mode

Create models in Asp.net MVC 5
In the picture above, we create a User table, so I will build the entity model for the User
*Click Models-> add class User.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MVC5_HelloWorld.Models
{
    public class User
    {
        [Key, Column(Order = 1)]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int idUser { get; set; }

        public string Username { get; set; }

        public string Password { get; set; }

        public int Lever { get; set; }

    }
}
Enter fullscreen mode Exit fullscreen mode

Create Class Connect Database extends DBContext
DBcontext used in Entity Framework, it's a very important part, connect to table in database and query execute (insert,update,detele)
Models/demoEntities.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVC5_HelloWorld.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVC5_HelloWorld.Models
{
    public class demoEntities : DbContext
    {
        public demoEntities() : base("demoASPEntities")
        {
        }
        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            modelBuilder.Entity<User>().ToTable("Users");
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            base.OnModelCreating(modelBuilder);


        }
    }
}
Enter fullscreen mode Exit fullscreen mode

base("demoASPEntities"): The declaration name connect
DbSet Users: We use The declaration table Users

Controllesr/HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC5_HelloWorld.Models;
namespace MVC5_HelloWorld.Controllers
{
    public class HomeController : Controller
    {
        private demoEntities _db = new demoEntities();
        // GET: Home
        public ActionResult Index()
        {
            var data = (from s in _db.Users select s).ToList();
            ViewBag.users = data;
             ViewBag.title = "MVC5 - Hello World";

            return View();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Views/Home/Index.cshtml edit as the code below

@model MVC5_HelloWorld.Models.User
    <div class="container">
        <div class="row">

            <div class="col-md-12">
                <h2>@ViewBag.title</h2>
                <a href="https://hoanguyenit.com" class="btn btn-success">https://hoanguyenit.com</a>
                <table class="table table-bordered">
                    @foreach (var user in ViewBag.users)
                    {
                    <tr>
                        <td>@user.Username</td>
                        <td>@user.Password</td>
                        <td>@{
                            if (user.Lever == 1)
                            {
                                <span class="badge badge-danger">Admin</span>
                            }
                            else
                            {
                                <span class="badge badge-warning">Member</span>
                            }
                        }</td>
                    </tr>

                    }
                </table>
            </div>
        </div>
    </div>
Enter fullscreen mode Exit fullscreen mode

Demo:
ASP.NET MVC 5 Using DBContext Connect Database -  hoanguyenit.com

Post:ASP.NET MVC 5 Using DBContext Connect Database

Top comments (1)

Collapse
 
yu_junjie0224 profile image
喻俊杰

Hello, I want to know how to edit my view page,This is my information model class,please help me!