ASP.NET MVC 5 Using DBContext Connect Database
Tags: csharp
Published: 2019-10-14 07:15:49

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
+ [ASP.NET MVC 5 Hello World](https://hoanguyenit.com/aspnet-mvc5-hello-world.html)
+ [ASP.NET MVC 5 Create Shared Layout Razor & ViewStart](https://hoanguyenit.com/aspnet-mvc5-create-shared-layout-razor-and-viewstart.html)
+ [ASP.NET MVC 5 Install Bootstrap](https://hoanguyenit.com/aspnet-mvc5-install-bootstrap.html)

**Install Entity Framework 6.x**
Tools->Nuget Package Manager
![ASP.NET MVC 5 Using DBContext Connect Database](https://thepracticaldev.s3.amazonaws.com/i/kqkva60v1ckb8dr9i124.jpg)

**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](https://thepracticaldev.s3.amazonaws.com/i/rcixkcetiivmhpg6wpd1.jpg)

After then, you open Web.config in project, add the following below code is connect database
```csharp
<connectionStrings>
    <add name="demoASPEntities" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=demomvc5;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\demomvc5.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
```
**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*
```csharp
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; }

    }
}
```
**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**
```csharp
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);


        }
    }
}
```

**base("demoASPEntities"):** The declaration name connect
**DbSet <User> Users:** We use The declaration table Users

**Controllesr/HomeController.cs**
```csharp
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();
        }
    }
}
```
**Views/Home/Index.cshtml** edit as the code below
```csharp
@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>
```

Demo:
![ASP.NET MVC 5 Using DBContext Connect Database -  hoanguyenit.com](https://thepracticaldev.s3.amazonaws.com/i/8o3t3obk27gubq2azjd1.jpg)

Post:[ASP.NET MVC 5 Using DBContext Connect Database](https://hoanguyenit.com/aspnet-mvc5-using-dbcontext-connect-database.html)