Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1143. C# - Entity Framework Core 6 개요 [링크 복사], [링크+제목 복사]
조회: 8648
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# - Entity Framework Core 6 개요

.NET 6로 ASP.NET Core Web App 프로젝트 템플릿으로 만든 기본 예제에서 시작해 볼까요? (전에도 콘솔 프로젝트에서 예제를 구성한 적이 있습니다.) ^^ 이후의 방법은 다음의 문서에서 자세하게 소개하고 있습니다.

Getting Started with EF Core
; https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli

정리하면, EF Core는 데이터베이스에 대한 ORM 층을 제공하는데, 따라서 결국 정해야 할 것은 ORM을 제공할 대상 "데이터베이스"가 됩니다. 즉, Sqlite, Microsoft SQL Server, Oracle, PostgreSQL,...에 따라 달라지는데요, 여기서는 SQL Server를 사용하는 것으로 가정하고 다음의 구성 요소를 참조 추가하겠습니다.

// 그 외에 데이터베이스의 제공자들 "Database Providers" 링크를 참고

Install-Package Microsoft.EntityFrameworkCore.SqlServer

참고로 .NET 6가 나오면서, EF Core도 6 버전이 나왔습니다. EF Core의 버전 정책은 그것이 지원하는 닷넷 버전과 일치합니다. 다시 말해, .NET Core 3.1 프로젝트라면 EF Core 3.x 버전을 설치해야 하는 식입니다. 위의 Nuget 설치는 최신 버전을 다운로드하므로 6.x의 EFCore 패키지를 참조하는 것이므로 반드시 .NET 6 이상의 프로젝트여야 합니다.

재미있는 것은 "EF Core 6"와 "EF 6"는 다른 제품이라는 점입니다. (주로 .NET Framework 지원을 위한) "EF 6"는 별도로 "Install-Package EntityFramework"와 같이 설치를 할 수 있는데, 향후 더 이상 지원이 계속되지 않을 것이라고 합니다. 따라서, 가능한 신규 프로젝트는 "EF 6"가 아닌 "EF Core 6"로 하시는 것이 좋습니다.




자, 그럼 필요한 패키지 참조를 했으니 DB 연동을 위한 코드를 작성해야겠지요?

이를 위해 데이터베이스와의 연동을 담당하는 DBContext와 개별 테이블에 해당하는 Entity들을 다음과 같이 만들어 줍니다.

using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace Intro
{
    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs => Set<Blog>();
        public DbSet<Post> Posts => Set<Post>();

        public BloggingContext() : base() { }

        public BloggingContext(DbContextOptions options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 테이블 이름을 변경하고 싶은 경우,
            // modelBuilder.Entity<Blog>().ToTable("Blog");
            // modelBuilder.Entity<Post>().ToTable("Post");
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; } = "";
        public int Rating { get; set; }
        public List<Post> Posts { get; set; } = new List<Post>();
    }

    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; } = new Blog();
    }
}




(대부분의 ORM 도구들처럼) 최초 응용 프로그램 실행 시 DB 구조가 없다면 이를 만들어야 하는데요, 이 과정은 Program.cs의 (.NET 5의 경우 Startup 클래스의 ConfigureServices/Configure) 코드 내에서 다음과 같이 할 수 있습니다.

// Program.cs

...[생략]...
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<BloggingContext>(
    options =>
    {
        string connectionString = builder.Configuration.GetConnectionString("BloggingDatabase");
        options.UseSqlServer(connectionString);
    });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}

using (var serviceScope = app.Services?.GetService<IServiceScopeFactory>()?.CreateScope())
{
    var ctx = serviceScope?.ServiceProvider.GetRequiredService<BloggingContext>();
    ctx?.Database.EnsureCreated();
}

...[생략]...

/* appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },

  "ConnectionStrings": {
    "BloggingDatabase": "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True"
  }
}
*/

/* Local SQL Server 연결 문자열
"TrustServerCertificate=true;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Blogging;Data Source=."
*/

그럼, Database.EnsureCreated에서 DB가 없으면 생성되는데, BloggingContext의 연결 문자열을 "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True"로 지정했으므로 LocalDB를 사용하게 됩니다.

SQL Server 2012에 포함된 LocalDB 기능 소개
; https://www.sysnet.pe.kr/2/0/1258

따라서 실제 생성된 DB 위치는 "%LOCALAPPDATA%\Microsoft\Microsoft SQL Server Local DB\Instances\mssqllocaldb"가 됩니다. (물론, LocalDB가 아닌 일반 SQL 서버를 사용하려면 그에 맞는 연결 문자열을 지정하면 됩니다.)




DB는 있는데, 초기 데이터가 없으면 심심하죠? ^^ 이를 위해 BloggingContext의 OnModelCreating을 재정의해 다음과 같은 seed 코드를 넣을 수 있습니다.

// Data Seeding
// https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding
public class BloggingContext : DbContext
{
    ...[생략]...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Blog>(b =>
        {
            b.HasData(new Blog { BlogId = 1, Url = "http://sample.com", Rating = 5 });
            b.OwnsMany(p => p.Posts).HasData(
                new { PostId = 1, Title = "새 글1", Content = "새글입니다.1", BlogId = 1 }, 
                new { PostId = 2, Title = "새 글2", Content = "새글입니다.2", BlogId = 1 });

            b.HasData(new Blog { BlogId = 2, Url = "http://test.com", Rating = 1 });
            b.OwnsMany(p => p.Posts).HasData(
                new { PostId = 3, Title = "새 글3", Content = "새글입니다.1", BlogId = 2 }, 
                new { PostId = 4, Title = "새 글4", Content = "새글입니다.2", BlogId = 2 });
        });
    }
}

/*
var blog = db.Blogs.Include(blog => blog.Posts)
.OrderBy(b => b.BlogId)
.FirstOrDefault();

if (blog == null)
{
    return;
}

Console.WriteLine("[posts]");
foreach (var item in blog.Posts)
{
    Console.WriteLine(item.Title);
}
*/

유의할 것은, 위의 data seed 과정은 DB가 없을 때만 유효합니다. 즉, 이미 빈 데이터베이스가 생성되었다면 위의 코드는 아무런 역할도 하지 않습니다.

이후의 데이터베이스에 대한 CRUD 과정은 일반적인 감각으로, 혹은 아래의 문서를 쓰윽 보시면,

Entity Framework Core
; https://learn.microsoft.com/en-us/ef/core/

금방 이해할 수 있을 것입니다. ^^




가장 최신 버전의 "Microsoft.EntityFrameworkCore.SqlServer" 구성 요소는 .NET Core 6 이상의 프로젝트에서만 설치가 됩니다. 그렇지 않으면 다음과 같은 식으로 설치 중에 오류가 발생합니다.

PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
Restoring packages for D:\workshop2\JenniferV\docker_sample\DockerNetSamples\razor_50_sample\razor_50_sample.csproj...
Install-Package : NU1202: Package Microsoft.EntityFrameworkCore.SqlServer 6.0.1 is not compatible with net5.0 (.NETCoreApp,Ve
rsion=v5.0). Package Microsoft.EntityFrameworkCore.SqlServer 6.0.1 supports: net6.0 (.NETCoreApp,Version=v6.0)
At line:1 char:1
+ Install-Package Microsoft.EntityFrameworkCore.SqlServer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
 
Install-Package : Package restore failed. Rolling back package changes for 'razor_50_sample'.
At line:1 char:1
+ Install-Package Microsoft.EntityFrameworkCore.SqlServer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

혹시 다음과 같은 오류를 또 만나게 된다면?

Error CS1061 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer' and no accessible extension method 'UseSqlServer' accepting a first argument of type 'DbContextOptionsBuilder' could be found (are you missing a using directive or an assembly reference?)


참조한 패키지가 "Microsoft.EntityFrameworkCore.SqlServer"인지 확인합니다. 실수로 "Microsoft.EntityFrameworkCore" 패키지를 참조하는 경우 UseSqlServer에 대한 확장 메서드가 없으므로 저런 오류가 발생합니다.

또한 본문의 예제를 docker support 환경에서 실행하면 Database.EnsureCreated 메서드에서 "'System.PlatformNotSupportedException' in Microsoft.Data.SqlClient.dll: 'LocalDB is not supported on this platform.'" 예외가 발생합니다. LocalDB는 윈도우 환경에서만 제공되므로 이것을 해결하려면 Standalone SQL Server 제품을 설치하고 그에 대한 연결 문자열을 사용하거나, 다른 DB로 우회해야 합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 2/24/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13450정성태11/21/20232255닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232354개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232629닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232487닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232419닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232705Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232456닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232493개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232322개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232654닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232354Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232846닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232462닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232661닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232896닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232833닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232631스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232357스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232408오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232723스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232614닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232871닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232927닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233104닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233287스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233104닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...