개발/C#

ASP.Net 메모용

지산동고라니 2023. 7. 26. 22:59
Your startup project 'TutorialShop.Api' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.

Microsoft.EntityFrameworkCore.Design 패키지가 없어서 발생하는 문제

 

dotnet add package Microsoft.EntityFrameworkCore.Design

Dotnet EntityFrameworkCore 설치

dotnet tool install --global dotnet-ef

Dotnet WebAPI Mysql(MairaDB) 연결방법

{
  "ConnectionStrings": {
    "Default" : "Server=localhost;Port=3306;Database=[Database Name];Uid=[userId];Pwd=[password]"
  },
  ...

}

DbContext 파일 생성

using Microsoft.EntityFrameworkCore;
using TutorialShop.Api.Entities;

namespace TutorialShop.Api.Data
{
    public class ShopDbContext : DbContext
    {
        public ShopDbContext(DbContextOptions<ShopDbContext> options) : base(options) { }

        public DbSet<Product>? Products { get; set; }
        public DbSet<Cart>? Carts { get; set; }
        public DbSet<CartItem>? CartItems { get; set; }
        public DbSet<User>? Users { get; set; }
        public DbSet<ProductCategory>? ProductCategorys { get; set; }
    }
}

Context Builder에 등록 (Program.cs)

builder.Services.AddDbContext<ShopDbContext>
    (options => options.UseMySql(builder.Configuration.GetConnectionString("Default"), ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("Default"))));

// default 는 ConnectionString에 등록한 Key

.Net 기초데이터 Migration (dBContext를 상속한 DBContext파일)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Product>().HasData(new Product
            {
                Id = 1,
                Name = "Glossier - Beauty Kit",
                Description = "A kit provided by Glossier, containing skin care, hair care and makeup products",
                ImageURL = "/Images/Beauty/Beauty1.png",
                Price = 100,
                Qty = 100,
                CategoryId = 1

            });

      // 반복...
}

Dotnet Migration Command

dotnet ef migrations add InitialCreate
dotnet ef database update