EF Core 시작

이 자습서에서는 Entity Framework Core를 사용하여 SQLite 데이터베이스에 대한 데이터 액세스를 수행하는 .NET Core 콘솔 앱을 만듭니다.

Windows에서 Visual Studio를 사용하거나 Windows, macOS 또는 Linux에서 .NET CLI를 사용하여 자습서를 진행할 수 있습니다.

GitHub에서 이 아티클의 샘플을 봅니다.

사전 요구 사항

다음 소프트웨어를 설치합니다.

새 프로젝트 만들기

dotnet new console -o EFGetStarted
cd EFGetStarted

Entity Framework Core 설치

EF Core를 설치하려면 대상으로 지정할 EF Core 데이터베이스 공급자에 대한 패키지를 설치합니다. 이 자습서에서는 .NET이 지원하는 모든 플랫폼에서 실행되는 SQLite를 사용합니다. 사용 가능한 공급자 목록은 데이터베이스 공급자를 참조하세요.

dotnet add package Microsoft.EntityFrameworkCore.Sqlite

모델 만들기

모델을 구성하는 컨텍스트 클래스 및 엔터티 클래스를 정의합니다.

  • 프로젝트 디렉터리에서 다음 코드를 사용하여 Model.cs를 만듭니다.
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public string DbPath { get; }

    public BloggingContext()
    {
        var folder = Environment.SpecialFolder.LocalApplicationData;
        var path = Environment.GetFolderPath(folder);
        DbPath = System.IO.Path.Join(path, "blogging.db");
    }

    // The following configures EF to create a Sqlite database file in the
    // special "local" folder for your platform.
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite($"Data Source={DbPath}");
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; } = new();
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

EF Core는 모델을 기존 데이터베이스에서 리버스 엔지니어링할 수도 있습니다.

팁: 이 애플리케이션은 명확성을 위해 의도적으로 단순하게 구성되었습니다. 연결 문자열은 프로덕션 애플리케이션에 대한 코드에 저장해서는 안 됩니다. 각 C# 클래스를 자체 파일로 분할하고 싶을 수도 있습니다.

데이터베이스 만들기

다음 단계에서는 마이그레이션을 사용하여 데이터베이스를 만듭니다.

  • 다음 명령을 실행합니다.

    dotnet tool install --global dotnet-ef
    dotnet add package Microsoft.EntityFrameworkCore.Design
    dotnet ef migrations add InitialCreate
    dotnet ef database update
    

    그러면 dotnet ef와 프로젝트에서 명령을 실행하는 데 필요한 디자인 패키지가 설치됩니다. migrations 명령은 마이그레이션을 스캐폴딩하여 모델에 대한 초기 테이블 집합을 만듭니다. database update 명령은 데이터베이스를 만들고 새 마이그레이션을 적용합니다.

만들기, 읽기, 업데이트 및 삭제

  • Program.cs를 열고 내용을 다음 코드로 바꿉니다.

    using System;
    using System.Linq;
    
    using var db = new BloggingContext();
    
    // Note: This sample requires the database to be created before running.
    Console.WriteLine($"Database path: {db.DbPath}.");
    
    // Create
    Console.WriteLine("Inserting a new blog");
    db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
    db.SaveChanges();
    
    // Read
    Console.WriteLine("Querying for a blog");
    var blog = db.Blogs
        .OrderBy(b => b.BlogId)
        .First();
    
    // Update
    Console.WriteLine("Updating the blog and adding a post");
    blog.Url = "https://devblogs.microsoft.com/dotnet";
    blog.Posts.Add(
        new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" });
    db.SaveChanges();
    
    // Delete
    Console.WriteLine("Delete the blog");
    db.Remove(blog);
    db.SaveChanges();
    

앱 실행

dotnet run

다음 단계