Hướng dẫn tạo Model với ngôn ngữ Razor trong ASP.NET Core trên Visual Studio

SolarWinds

Super Moderate
Nov 16, 2006
51,317
25
48
Hanoi
www.hanoiyeu.com
320x50.jpg


Mục lục bài viết


Tiếp tục chuỗi bài học về ASP.NET Core Web APP. Sau đây oktot sẽ giới thiệu với các bạn bài tiếp theo là Hướng dẫn tạo Model với ngôn ngữ razor trong ASP.NET Core. Nếu bạn chưa muốn tìm hiểu ASP.NET Core là gì thì có thể xem lại bài trước: ASP.NET Core bước đột phá trong công nghệ .NET.

Trong bài này oktot sẽ giới thiệu cho bạn cách tạo model để quản lí rạp chiếu phim (movies) trên database, đồng thời sử dụng các lớp (class) trong entity framework core (EF Core) để làm việc với Database.

EF Core là một mô hình ánh xạ đối tượng (ORM) giúp đơn giản hóa việc viết mã code để truy cập Database. bạn cũ có thể tự viết code truy cập database nếu không sử dụng EF Core nếu thật sự cần thiết.

Các lớp (class) mô hình (model) bạn tạo ra gọi là các lớp POCO (plain-old CLR objects) bởi vì chúng không có bất kì sự phụ thuộc nào trên EF Core. Chúng xác định các thuộc tính của dữ liệu được lưu trữ trong cơ sở dữ liệu.

Trong ví dụ này trước hết bạn phải tạo ra database mẫu.


Link download Source mẫu:


Sau khi tải Source mẫu chúng ta sẽ bắt đầu trên visual studio.

1. Tạo data model trên visual studio


Trên Solution Explorer, nhấn chuột phải vào RazorPagesMovie project > Add > New Folder. Thư mục tên Models.

Chọn chuột phải vào thư mục Models. Tiếp tục chọn Add > Class. Đặt tên cho lớp Movie và thay thế nội dung của lớp Movie bằng đoạn mã sau:


using System; using System.ComponentModel.DataAnnotations.Schema; namespace RazorPagesMovie.Models { public class Movie { public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } } }



1

2

3

4

5

6

7

8

9

10

11

12

13

14


using System;

using System.ComponentModel.DataAnnotations.Schema;

namespace RazorPagesMovie.Models

{

public class Movie

{

public int ID { get; set; }

public string Title { get; set; }

public DateTime ReleaseDate { get; set; }

public string Genre { get; set; }

public decimal Price { get; set; }

}

}

Hình 1. Code Tạo model Movie

2. Hướng dẫn cài đặt nền tảng cơ bản (Scaffold the movie model)


Trong phần này, chúng ta sẽ tạo ra các trang Add, Update, Delete trong các trang.

Tạo Pages/Movies:

  • Click phải vào thư mục Pages chọn Add > New Folder.
  • Tên thư mục là Movies

Click phải vào thư mục Pages/Movies folder > Add > New Scaffolded Item.

sca.png


add_scaffold.png


Hoàn tất Add Razor Pages sử dụng Entity Framework (CRUD) dialog:

arp.png


The scaffold sẽ xử lý tạo và update file như sau:

Files created

  • Pages/Movies: Create, Delete, Details, Edit, and Index.
  • Data/RazorPagesMovieContext.cs
File updated

  • Startup.cs
3. Initial migration


Trong phần này sẽ hướng dẫn các bạn sử dụng Package Manager Console (PMC) trên visual studio:

  • Add an initial migration.
  • Update the database with the initial migration.

Từ thanh Tools menu, Chọn NuGet Package Manager > Package Manager Console.

pmc.png


Trên PMC, Nhập đoạn code dưới đây:


Add-Migration Initial Update-Database



Add-Migration Initial

Update-Database

Việc di chuyển ef thêm lệnh tạo lệnh Initial Create để tạo lược đồ cơ sở dữ liệu ban đầu. Dựa trên mô hình được chỉ định trong DbContext (Trong tệp Models / RazorPagesMovieContext.cs)

Đối số InitialCreate được sử dụng để đặt tên cho các di chuyển, bất kỳ tên nào cũng có thể được sử dụng, nhưng theo quy ước, một tên được chọn để mô tả việc di chuyển.

The ef database update command runs the Up method in the Migrations/<time-stamp>_InitialCreate.cs file. The Up method creates the database.

Kiểm tra context registered với dependency injection (DI)

ASP.NET Core được xây dựng với DI. Các thành phần yêu cầu các dịch vụ này (chẳng hạn như Razor Pages) được cung cấp các dịch vụ này thông qua các tham số của hàm tạo. Mã hàm xây dựng nhận một cá thể ngữ cảnh DB được hiển thị sau trong hướng dẫn.

Kiểm tra hàm Startup.ConfigureServices các đánh dấu được thêm với scaffolder:


// This method gets called by the runtime. // Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is // needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext<RazorPagesMovieContext>(options => options.UseSqlServer( Configuration.GetConnectionString("RazorPagesMovieContext"))); }



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18


// This method gets called by the runtime.

// Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)

{

services.Configure<CookiePolicyOptions>(options =>

{

// This lambda determines whether user consent for non-essential cookies is

// needed for a given request.

options.CheckConsentNeeded = context => true;

options.MinimumSameSitePolicy = SameSiteMode.None;

});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

services.AddDbContext<RazorPagesMovieContext>(options =>

options.UseSqlServer(

Configuration.GetConnectionString("RazorPagesMovieContext")));

}

RazorPagesMovieContext


using Microsoft.EntityFrameworkCore; namespace RazorPagesMovie.Models { public class RazorPagesMovieContext : DbContext { public RazorPagesMovieContext (DbContextOptions<RazorPagesMovieContext> options) : base(options) { } public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; } } }



1

2

3

4

5

6

7

8

9

10

11

12

13

14


using Microsoft.EntityFrameworkCore;

namespace RazorPagesMovie.Models

{

public class RazorPagesMovieContext : DbContext

{

public RazorPagesMovieContext (DbContextOptions<RazorPagesMovieContext> options)

: base(options)

{

}

public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; }

}

}

Demo sau khi hoàn tất

conan.png