DEV Community

Cover image for Create Database using Code First in ASP.NET CORE 2.1
Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

Create Database using Code First in ASP.NET CORE 2.1

First, We have create ASP.NET Core 2.1 , in the article previous. Today, we use EntityFramework Core in ASP.NET Core 2.1, we use Code-First set up propeties class model
You like use Database, can import it to Project, you can see it Code-First : https://www.entityframeworktutorial.net/code-first/what-is-code-first.aspx
After when create project, you set up 3 plugin, you choose version 2.14

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer : support connect SQL SERVER
Microsoft.EntityFrameworkCore.Tools : support command migration
Enter fullscreen mode Exit fullscreen mode

Set up connect to SQL SERVER, open appsetting.json file

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

We need set up class Product & Category, go to Models folder, create it

  • Models/Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ShopAspCore.Models
{
    public class Product
    {
        public int idProduct { get; set; }
        public string Title { get; set; }
        public string UrlImage { get; set; }
        public string Price { get; set; }
        public string Detail { get; set; }
        public int idCategory { get; set; }
        public Category Category { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

In the Models / Product.cs file above, we say that the Product belongs to a certain category

  • Models/Category.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ShopAspCore.Models
{
    public class Category
    {
        public int idCategory { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }

    }
}'
Enter fullscreen mode Exit fullscreen mode

With the Models / Category.cs file: we say that a Category has many Products
Okay, continue, we need create DBContext class, use connect to SQL SERVER

  • Models/EFDdataContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace ShopAspCore.Models
{
    public class EFDataContext : DbContext
    {
        public EFDataContext(DbContextOptions<EFDataContext> options)
               : base(options)
        {

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //config primary key(Product & Category)
            modelBuilder.Entity<Product>().HasKey(s => s.idProduct);
            modelBuilder.Entity<Category>().HasKey(s => s.idCategory);

            //configuration relationship table(Product & Category)
            modelBuilder.Entity<Product>()
                .HasOne(s => s.Category)
                .WithMany(s => s.Products)
                .HasForeignKey(s => s.idCategory)
                .OnDelete(DeleteBehavior.Restrict);


        }
        public DbSet<Product> Products { get; set;}
        public DbSet<Category> Categories { get; set; }

    }
}
Enter fullscreen mode Exit fullscreen mode

The code above, we set up relationship (Product, Category)
Open Startup.cs file, modify it the following code below

using System;
using System.Collections.Generic;
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 ShopAspCore.Models;
using Microsoft.EntityFrameworkCore;
namespace ShopAspCore
{
    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?}");
            });
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Ok the setup is done, now we Nutget Package Manager->Package Manager Console, run Migration

Add-Migration shopcore
Update-Database
Enter fullscreen mode Exit fullscreen mode

After then , when we run command migration, we see Migrations folder in Project and Database in SQL SERVER, you can open SQL SERVER see it
Create Database using Code First in ASP.NET CORE 2.1 - hoanguyenit.com
Create Database using Code First in ASP.NET CORE 2.1 - hoanguyenit.com
Create Database using Code First in ASP.NET CORE 2.1 - hoanguyenit.com
The Article : Create Database using Code First in ASP.NET CORE 2.1

Top comments (0)