🔎 유용한 정보
1. 강의 개요
이번 강의에서는 **Entity Framework (EF)**를 사용하여 Windows Forms 애플리케이션과 데이터베이스를 연동합니다.
EF는 ORM(Object Relational Mapping) 도구로, SQL을 직접 작성하지 않고도 객체 지향적으로 데이터를 관리할 수 있습니다.
Code-First 방식을 사용해 데이터베이스를 설계하고,
CRUD(Create, Read, Update, Delete) 기능을 구현합니다.
2. 학습 목표
- Entity Framework를 Windows Forms 프로젝트에 통합
- Code-First 방식으로 데이터 모델 생성
- DbContext를 사용한 데이터베이스 관리
- CRUD 기능 구현
3. 기능 요구사항
필수 기능
1️⃣ Code-First 방식으로 데이터베이스 설계:
- 클래스(모델)를 기반으로 데이터베이스 및 테이블 자동 생성
2️⃣ CRUD 기능 구현:
- 데이터를 추가(Create), 조회(Read), 수정(Update), 삭제(Delete)
3️⃣ DataGridView를 활용한 데이터 표시:
- Entity Framework를 통해 데이터베이스의 내용을 시각화
4️⃣ 폼 기반 입력 및 데이터 관리:
- 사용자 입력(TextBox)을 통해 데이터를 추가하고, UI로 데이터를 관리
4. 실습: Entity Framework 연동 및 CRUD 구현
1️⃣ 사전 준비
- NuGet 패키지 설치:
- Visual Studio에서 NuGet 패키지 관리를 열고 다음 패키지를 설치합니다:
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
- Visual Studio에서 NuGet 패키지 관리를 열고 다음 패키지를 설치합니다:
- SQL Server 설정:
- SQL Server가 실행 중이어야 합니다.
- Connection String에서 SQL Server 인스턴스와 데이터베이스 이름을 지정합니다.
2️⃣ 폼 구성
- 폼(Form) 이름: Form1
- 컨트롤 배치
컨트롤 타입 이름 위치 크기
DataGridView | dgvData | 폼 중앙 | (500 x 300) |
TextBox | txtName | 폼 상단 왼쪽 | (150 x 30) |
TextBox | txtAge | 폼 상단 중앙 | (150 x 30) |
Button | btnAdd | 폼 상단 오른쪽 | (80 x 30) |
Button | btnUpdate | 폼 하단 왼쪽 | (80 x 30) |
Button | btnDelete | 폼 하단 오른쪽 | (80 x 30) |
📌 폼 디자인 예시:
-------------------------------------------
| [Name: TextBox] [Age: TextBox] [Add버튼] |
-------------------------------------------
| [DataGridView - 데이터 표시] |
-------------------------------------------
| [Update 버튼] [Delete 버튼] |
-------------------------------------------
3️⃣ 코드 작성
(1) 데이터 모델 생성
using System.ComponentModel.DataAnnotations;
namespace WindowsFormsApp_EF
{
public class Person
{
[Key]
public int Id { get; set; } // 기본 키
[Required]
public string Name { get; set; } // 이름
[Range(0, 120)]
public int Age { get; set; } // 나이
}
}
(2) DbContext 클래스 생성
using Microsoft.EntityFrameworkCore;
namespace WindowsFormsApp_EF
{
public class AppDbContext : DbContext
{
public DbSet<Person> People { get; set; } // People 테이블
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=localhost;Database=MyEFDatabase;Trusted_Connection=True;");
}
}
}
(3) CRUD 기능 구현
using System;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp_EF
{
public partial class Form1 : Form
{
private readonly AppDbContext _dbContext;
public Form1()
{
InitializeComponent();
_dbContext = new AppDbContext();
_dbContext.Database.EnsureCreated(); // 데이터베이스 생성
LoadData();
}
// 데이터 로드
private void LoadData()
{
dgvData.DataSource = _dbContext.People.ToList(); // DbSet에서 데이터 로드
}
// 데이터 추가
private void btnAdd_Click(object sender, EventArgs e)
{
string name = txtName.Text.Trim();
int age = int.TryParse(txtAge.Text, out int result) ? result : 0;
if (string.IsNullOrEmpty(name) || age <= 0)
{
MessageBox.Show("유효한 이름과 나이를 입력하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var newPerson = new Person { Name = name, Age = age };
_dbContext.People.Add(newPerson);
_dbContext.SaveChanges(); // 데이터 저장
LoadData();
ClearInputs();
}
// 데이터 수정
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dgvData.SelectedRows.Count == 0)
{
MessageBox.Show("수정할 행을 선택하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int id = Convert.ToInt32(dgvData.SelectedRows[0].Cells["Id"].Value);
var person = _dbContext.People.Find(id);
if (person != null)
{
person.Name = txtName.Text.Trim();
person.Age = int.TryParse(txtAge.Text, out int result) ? result : 0;
_dbContext.SaveChanges(); // 변경 사항 저장
}
LoadData();
ClearInputs();
}
// 데이터 삭제
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvData.SelectedRows.Count == 0)
{
MessageBox.Show("삭제할 행을 선택하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int id = Convert.ToInt32(dgvData.SelectedRows[0].Cells["Id"].Value);
var person = _dbContext.People.Find(id);
if (person != null)
{
_dbContext.People.Remove(person);
_dbContext.SaveChanges(); // 데이터 삭제
}
LoadData();
}
// 입력 필드 초기화
private void ClearInputs()
{
txtName.Text = "";
txtAge.Text = "";
}
}
}
4️⃣ 실행 결과
1️⃣ 데이터 추가
- 이름과 나이를 입력하고 "Add" 버튼 클릭 → 데이터베이스에 저장
2️⃣ 데이터 수정
- DataGridView에서 행을 선택 → TextBox로 데이터 수정 후 "Update" 버튼 클릭
3️⃣ 데이터 삭제
- DataGridView에서 행을 선택 → "Delete" 버튼 클릭
4️⃣ DataGridView 업데이트
- 데이터베이스 변경 사항이 실시간으로 반영
5. 주요 개념 요약
- Entity Framework: SQL 쿼리 없이 데이터베이스를 조작할 수 있는 ORM 도구
- DbContext: 데이터베이스와의 상호작용을 관리
- Code-First: 클래스(모델)를 기반으로 데이터베이스 및 테이블을 생성
- CRUD: Create, Read, Update, Delete 기능 구현
'📁 [4] 개발자 정보 & 코드 노트 > C#' 카테고리의 다른 글
C# Windows Forms 강의 65편: 데이터 바인딩(Data Binding)을 활용한 사용자 인터페이스 개선 (0) | 2025.04.09 |
---|---|
C# Windows Forms 강의 64편: LINQ를 활용한 데이터 필터링 및 검색 (0) | 2025.04.08 |
C# Windows Forms 강의 62편: MySQL 서버와 연동하여 CRUD 구현 (0) | 2025.04.06 |
C# Windows Forms 강의 61편: SQLite 데이터베이스와 Windows Forms 연동 (0) | 2025.04.05 |
C# Windows Forms 강의 60편: TableLayoutPanel과 Dynamic Controls로 UI 동적 생성하기 (0) | 2025.04.04 |
🔎 유용한 정보