Kết nối cơ sở dữ liệu với ASP.NET Core

0
5012

Chào mọi người! Tiếp tục loại bài hướng dẫn ASP.NET Core Web app trên Windows với visual studio 2017. Ở bài trước chúng ta đã tìm hiểu về Hướng dẫn tạo Scaffolded Razor Pages trên ASP.NET Core còn bây giờ chúng ta sẽ tiếp tục tìm hiểu việc kết nối và làm việc của ASP.NET Core với cơ sở dữ liệu(database) như thế nào?

RazorPagesMovieContext là đối tượng giúp xử lí công việc kết nối với cơ sở dữ liệu và mapping(ánh xạ) của Movie class tới các bảng ghi của cơ sở dữ liệu.

Database context được đăng kí trong DI (Dependency injection) chứa trong phương thức ConfigureServices của file Startup.cs với nội dung như sau:

// 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")));
}

Để biết thêm thông tin về các phương thức được sử dụng trong ConfigureServices có thể tham khảo link bên dưới:

Trong ASP.NET Core việc cấu hình chuối kết nối hiển thị ở biến ConnectionString. Cho ứng dụng được phát triển trên local. Thông tin cơ sở dữ liệu được lấy từ file appsettings.json.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-1234;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Khi mà ứng dụng được triển khai để Test hay chạy thật trên server thì cần tìm hiểu thêm cấu hình môi trường của server để có thể chạy ứng dụng một cách tối ưu nhất.

Sau đây là hướng kết nối với Cơ sở dữ liệu trên Visual studio với SQL Server Express LocalDB:

LocalDB là phiên bản gọn nhẹ của công cụ cơ sở dữ liệu SQL Server Express được nhắm mục tiêu phát triển chương trình. LocalDB bắt đầu theo yêu cầu và chạy trong chế độ người dùng, vì vậy không có cấu hình phức tạp. Theo mặc định, cơ sở dữ liệu LocalDB tạo các tệp * .mdf trong thư mục C: / Users / <user />.

Từ View trên thanh menu nhấn chọn SQL Server Object Explorer (SSOX).

Nhấn chuột phải trên bảng Movie rồi chọn View Designer:

Sau khi chọn sẽ xuất hiện như hình bên dưới:

Nhấp chuột phải vào bảng Movie và chọn Xem dữ liệu:

Seed the database

Tạo một lớp mới có tên SeedData trong thư mục Mô hình với code sau:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace RazorPagesMovie.Models
{
    public static class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new RazorPagesMovieContext(
                serviceProvider.GetRequiredService<
                    DbContextOptions<RazorPagesMovieContext>>()))
            {
                // Look for any movies.
                if (context.Movie.Any())
                {
                    return;   // DB has been seeded
                }

                context.Movie.AddRange(
                    new Movie
                    {
                        Title = "When Harry Met Sally",
                        ReleaseDate = DateTime.Parse("1989-2-12"),
                        Genre = "Romantic Comedy",
                        Price = 7.99M
                    },

                    new Movie
                    {
                        Title = "Ghostbusters ",
                        ReleaseDate = DateTime.Parse("1984-3-13"),
                        Genre = "Comedy",
                        Price = 8.99M
                    },

                    new Movie
                    {
                        Title = "Ghostbusters 2",
                        ReleaseDate = DateTime.Parse("1986-2-23"),
                        Genre = "Comedy",
                        Price = 9.99M
                    },

                    new Movie
                    {
                        Title = "Rio Bravo",
                        ReleaseDate = DateTime.Parse("1959-4-15"),
                        Genre = "Western",
                        Price = 3.99M
                    }
                );
                context.SaveChanges();
            }
        }
    }
}
if (context.Movie.Any())
{
    return;   // DB has been seeded.
}

Add the seed initializer

Trong Program.cs, sửa đổi phương thức Main để làm như sau:

  • Get a DB context instance from the dependency injection container.
  • Call the seed method, passing to it the context.
  • Dispose the context when the seed method completes
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RazorPagesMovie.Models;
using System;
using Microsoft.EntityFrameworkCore;

namespace RazorPagesMovie
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context=services.
                        GetRequiredService<RazorPagesMovieContext>();
                    context.Database.Migrate();
                    SeedData.Initialize(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

 

Kết quả khi chạy trên localhost:

 

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.