Database Relationships(One to Many, Many to Many) in ASP.NET CORE 2.1

Trong bày này mình sẽ kết nối (One to Many)(Many to Many) dùng Fluent API in EF Core, bạn có thể xem thêm tại đây: https://www.entityframeworktutorial.net/efcore/entity-framework-core.aspx
Đầu tiên bạn tạo một project ASP.NET CORE 2.1->Chọn mô hình MVC, để tự project xây dựng cấu trúc sẵn cho ta
Tiếp theo bạn cần cài đặt Entityframwork core cho mình, cài đặt 3 thư viện sau, hãy mở Nutget lên và install nó

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

Thêm chuổi ConnectionStrings trong file appsetting.json để connect tới SQL SERVER

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "EFDataContext": "Server=DESKTOP-GCABV8F\\SQLExpress;Database=DBcore;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Bên trên bạn đặt database tùy ý, tên gì cũng được, bởi vì hồi ta chạy migration nó sẽ tự tạo datbase cho ta trong SQL SERVER
Okay, giờ ta có mô hình dữ liệu như dưới đây và ta tiến hành tạo các class mô hình đó trong thư mục Models

- User -> HasMany(Role) => CREATE class Models/User.cs [idUser,Name,Age]
- Role -> HasMany(User) => CREATE class Models/Role.cs [idRole,Name]
- UserRole -> WithOne(Role,User) => CREATE class Models/UserRole.cs [idRole,idUser]
- User -> HasMany(Post)
- Post -> WithOne(User) => CREATE class Models/Post.cs [idPost,Title,Body,idUser]

+ Models/User.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RelationshipCoreFirst_ASPcore.Models
{
    public class User
    {
        public int idUser { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public virtual ICollection<UserRole> UserRoles { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
    }
}

+ Models/Role.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RelationshipCoreFirst_ASPcore.Models
{
    public class Role
    {
        public int idRole { get; set; }
        public string Name { get; set; }
        public virtual ICollection<UserRole> UserRoles { get; set; }
    }
}

+ Models/UserRole.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RelationshipCoreFirst_ASPcore.Models
{
    public class UserRole
    {
        public int idUser { get; set; }
        public int idRole { get; set; }
        public User User { get; set; }
        public Role Role { get; set; }
    }
}

+ Models/Post.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RelationshipCoreFirst_ASPcore.Models
{
    public class Post
    {
        public int idPost { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public int idUser { get; set; }
        public User User { get; set; }
    }
}

Sau khi ta đã tạo các class trên xong, tiếp theo ta cần tạo DBContext
DbContext là một lớp quan trọng trong Entity Framework. Nó là cầu nối giữa của các lớp thực thể và cơ sở dữ liệu.
Tạo EFDataContext.cs trong thư mục Models
+ Models/EFDataContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace RelationshipCoreFirst_ASPcore.Models
{
    public class EFDataContext : DbContext
    {
        public EFDataContext(DbContextOptions<EFDataContext> options)
               : base(options){}
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //config primary key(Role, User,Post,UserRole)
            modelBuilder.Entity<Post>().HasKey(s => s.idPost);
            modelBuilder.Entity<User>().HasKey(s => s.idUser);
            modelBuilder.Entity<Role>().HasKey(s => s.idRole);
            modelBuilder.Entity<UserRole>().HasKey(s =>
               new {
                   s.idUser,
                   s.idRole
               });

            //configuration relationship table(User & Post)
            modelBuilder.Entity<Post>()
                .HasOne(s => s.User)
                .WithMany(s => s.Posts)
                .HasForeignKey(s => s.idUser)
                .OnDelete(DeleteBehavior.Restrict);


            // Relationships table User,Role,UserRole
            modelBuilder.Entity<UserRole>()
              .HasOne<User>(sc => sc.User)
              .WithMany(s => s.UserRoles)
              .HasForeignKey(sc => sc.idUser);

            modelBuilder.Entity<UserRole>()
                .HasOne<Role>(sc => sc.Role)
                .WithMany(s => s.UserRoles)
                .HasForeignKey(sc => sc.idRole);
        }
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<UserRole> UserRoles { get; set; }
        public DbSet<Post> Posts { get; set; }
       

    }
}

Đoạn mã trên ta thiết lập khai báo các khóa chính, đồng thời cài đặt mối liên kết giữa các table với nhau
Okay, giờ ta cần khai báo class EFDataContext.cs đến file Startup.cs để gọi nó, bạn thêm câu lệnh sau vào hàm ConfigureServices

services.AddDbContext<EFDataContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("EFDataContext")));

Đồng thời thêm ta cần khai báo thư viện EntityFrameworkCore và đường dẫn Models chưa class EFDataContext.cs của ta, copy 2 câu lệnh dưới để vào Startup.cs
using Microsoft.EntityFrameworkCore;
using RelationshipCoreFirst_ASPcore.Models;

+ Startup.cs(FullCode)

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using RelationshipCoreFirst_ASPcore.Models;
namespace RelationshipCoreFirst_ASPcore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // 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_1);
            services.AddDbContext<EFDataContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("EFDataContext")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Ok, vậy là xong, giờ ta cần chạy lệnh migration để tạo Database và Table, bạn vào Tools->Nutget Packager Manager->Package Manager Console, rồi chạy lệnh dưới đây
add-migration dbcore_v1
Sau khi chạy lệnh trên xong, bạn sẽ mình thấy thư mục Migrations trong project của bạn
Tiếp theo chạy lệnh tạo database, dùng câu lệnh dưới đây
update-database
Sau khi chạy xong, bạn mở SQL SERVER lên sẽ thấy database mới được vừa tạo


 Github:https://github.com/skipperhoa/database-relationship-aspnet-core21

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)