Entity Framework

2. Visual Studio에서 Blazor + Entity Framework 시작하기

샐님 2024. 1. 13. 12:17
728x90
반응형

1.  Order 모델 생성 후 Customer 모델의 외래키 적용

 1) Order 모델 생성

using System.ComponentModel.DataAnnotations;

namespace EntityFrameworkTest.Data.Model
{
    public class Order
    {
        [Key]
        public int Id { get; set; }
        public string? ItemDescription { get; set; }
        public int Quantity { get; set; }
        public Customer Customer { get; set; }
    }
}

 

2) Db Set 추가

using EntityFrameworkTest.Data.Model;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;

namespace EntityFrameworkTest.Data
{
    public class DemoDbContext : DbContext
    {
        public DemoDbContext(DbContextOptions<DemoDbContext> options) : base(options)
        {
        }


       
        public DbSet<Customer> customers { get; set; }
        public DbSet<Order> orders { get; set; }
    }
}

 

3) 패키지 콘솔 명령 입력

- Add-Migration "added-order_table"

- customer 테이블을 외래키로 생성된 것 확인

 

20240113022620_Added_Orders_Table.cs 파일

using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace EntityFrameworkTest.Migrations
{
    public partial class Added_Orders_Table : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "orders",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    ItemDescription = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Quantity = table.Column<int>(type: "int", nullable: false),
                    CustomerId = table.Column<int>(type: "int", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_orders", x => x.Id);
                    table.ForeignKey(
                        name: "FK_orders_customers_CustomerId",
                        column: x => x.CustomerId,
                        principalTable: "customers",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_orders_CustomerId",
                table: "orders",
                column: "CustomerId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "orders");
        }
    }
}

 

** 실제 blazor 에서 데이터베이스와 상호 작용하는 데이터를 사용할 수 있다. **

2. 새 고객 추가 화면 생성

1)  Customer Service 파일 생성 

 * Service : 프론트엔드와 데이터베이스 사이의 중간 계층과 비슷

 - Services 폴더 생성

 - CustomerService.cs 생성

 

using EntityFrameworkTest.Data;
using EntityFrameworkTest.Data.Model;
using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkTest.Services
{
    public class CustomerService
    {
        private IDbContextFactory<DemoDbContext> _dbContextFactory;

        // customer service 클래스의 생성자에 송족성 주입을 통해 초기화했으므로
        // // 몇가지 작업을 통해 모든 종류의 쿼리 업데이트 및 검색을 처리하는 함수 생성
        public CustomerService(IDbContextFactory<DemoDbContext> dbContextFactory)
        {
            _dbContextFactory = dbContextFactory;   
        }

        public void AddCustomer(Customer customer)
        {
            using(var context = _dbContextFactory.CreateDbContext())
            {
                context.customers.Add(customer);
                // 변경사항을 데이터베이스에 저장
                context.SaveChanges();
            }
        }

        public Customer GetCustomerByName(string name) 
        {
            using (var context = _dbContextFactory.CreateDbContext())
            {
                var customer = context.customers.SingleOrDefault(x => x.Name == name);
                return customer;
            }
        }

        public void UpdateCustomerByName(string name, int age)
        {
            var customer = GetCustomerByName(name);
            if(customer == null)
            {
                throw new Exception("customer dose not exist. Cannot update.");
            }

            customer.Age = age;
            using(var context = _dbContextFactory.CreateDbContext())
            {
                context.Update(customer);
                context.SaveChanges();
            }
        }
    }
}

-  context.SaveChanges(); 를 통해 실제 db에 변경 사항을 업데이트 할 수 있다. 

3) 프론트엔드 화면 생성

@page "/"
@using EntityFrameworkTest.Services
@using EntityFrameworkTest.Data.Model
@inject CustomerService customerService;

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<EditForm Model="@customer" OnValidSubmit="HandleSubmit">
    <label for="NameInput">Name</label>
    <InputText id="NameInput" @bind-Value="@customer.Name"></InputText>
    <label for="AgeInput">Age</label>
    <InputNumber id="AgeInput" @bind-Value="@customer.Age"></InputNumber>
    <button type="submit" class="btn-primary">Create</button>
</EditForm>

@code{
    Customer customer = new Customer();

    public void HandleSubmit(EditContext editContext)
    {
        var newCustomer = (Customer)editContext.Model;
        newCustomer.CreateDate = DateTime.Now;
        customerService.AddCustomer(newCustomer);
    }
}

 

** Entity Framework 는 sql 쿼리 대부분 사용가능하며 , 원시적으로 sql 쿼리를 작성했을 때 발생하는 위험 부담을 줄일 수 있다. 

728x90
반응형