Hướng dẫn làm đăng nhập bằng entity faremwork

Ở bài này mình sẽ hướng dẫn các bạn làm ứng dụng web CRUD [Create, Read, Update, Delete] quản lý sản phẩm đơn giản.

Kiến thức của bài

  • Sử dụng Entity Framework 6 code first MVC5 database sử dụng SQL Server 2014.
  • Data Migration
  • Sử dụng ViewModel để hiển thị thông tin.

Cần chuẩn bị

  1. Visual Studio 2013 trở lên.
  2. SQL Server 2012 trở lên.
  3. Entity Framework [EntityFramework NuGet package].
  4. .NET 4.5 trở lên.

Tạo ứng dụng Web

Cài đặt package Entity Framework 6

Có 2 cách để bạn cài đặt 1 package:

  1. Sử dụng Manage NutGet Packages.**

2. Sử dụng Package manager console.

Tạo model

Phân tích qua một chút ở đây mình sẽ tạo 2 model đó là model Product và model CategoryOfProduct. Trong Product là model thể hiển thông tin sản phẩm sẽ có các thuộc tính sau: ProductID, NameOfProduct, CategoryOfProductID. CategoryOfProduct model thể hiện thông tin loại sản phẩm sẽ có các thuộc tính sau: CategoryOfProductID, Description. Quan hệ giữa Product và CategoryOfProduct là quan hệ 1 - n tức là 1 CategoryOfProduct có nhiều Product vì vậy phải đặt khóa chính của CategoryOfProduct làm khóa ngoại cho Product. Mô tả bằng hình ảnh dưới đây:

Trong thư mục Models tạo class Product.cs, bạn có thể theo dõi code dưới đây:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProductManagement.Models
{
    public class Product
    {
        public int ProductID { get; set; }
        public string NameOfProduct { get; set; }
        public int CategoryOfProductID { get; set; }
    }
}

Cũng trong thư mục Models bạn tạo tiếp class CategoryOfProduct.cs, bạn có thể theo dõi code dưới đây:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProductManagement.Models
{
    public class CategoryOfProduct
    {
        public int CategoryOfProductID { get; set; }
        public string Description { get; set; }
    }
}

Kết nối với SQL Server bằng Visual Studio

  • Trên thanh toolbars của VS bạn vào View => Server Explorer.
  • Sau đó trên cửa sổ Server Explorer bạn chọn vào icon mình đã khoanh đỏ để tạo mới connection đến SQL Server.

Tạo lớp DatabaseContext

namespace ProductManagement.Models
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    public partial class ProductDBContext : DbContext
    {
        public ProductDBContext[]
            : base["name=ProductDBContext"]
        {
        }
        public DbSet Products { get; set; }
        public DbSet CategoryOfProducts { get; set; }
        protected override void OnModelCreating[DbModelBuilder modelBuilder]
        {
        }
    }
}

Tạo mới CategoryOfProductController

Thêm đường dẫn của Views vào Layout

  • Trong thư mục Views => Shared => _Layout.cshtml
  • Bạn thêm dòng code này vào`
  • @Html.ActionLink["Category Of Product", "Index", "CategoryOfProducts"]
  • `

Tạo mới ProductController

Sử dụng Code first Migrations.

  • Enable Migration
    • Mở cửa sổ làm việc Package mangager consoles nhập đoạn code này Enable-Migrations để thực enable migration.
    • Sau khi enable xong thư mục Migrations sẽ tự động được tạo ra, trong đó có file Initial Create và Configuration
  • Khởi tạo dữ liệu
    • Trong file Configuration insert đoạn code sau vào phướng thức Seed
       //  You can use the DbSet.AddOrUpdate[] helper extension method  
       //  to avoid creating duplicate seed data.  
       context.CategoryOfProducts.AddOrUpdate[c => c.CategoryOfProductID,  
           new Models.CategoryOfProduct{ CategoryOfProductID = 1, Description = @"Đồ điện tử" },  
           new Models.CategoryOfProduct { CategoryOfProductID = 2, Description = @"Đồ nhà bếp"}  
           ];  
       context.Products.AddOrUpdate[p => p.ProductID,  
           new Models.Product { ProductID = 1, NameOfProduct = @"Quạt điện", CategoryOfProductID = 1},  
           new Models.Product { ProductID = 2, NameOfProduct = @"Chảo", CategoryOfProductID = 2}  
           ];  
      
  • Để insert dữ liệu khởi tạo vào database thực hiện UpdateDatabase chèn đoạn code sau vào Package mangager consoles Update-Database

Sau khi update xong vào SQL để xem đã insert được vào cơ sở dữ liệu chưa sử dụng Server Explorer trên VS.

Chủ Đề