Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1143. C# - Entity Framework Core 6 개요 [링크 복사], [링크+제목 복사]
조회: 8618
글쓴 사람
정성태 (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)
13598정성태4/16/2024212닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024294닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024511닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024528닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024758닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/2024949닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241186C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241155닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241070Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241132닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241185닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241136오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241266Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241089Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241044개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241145Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241218Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241366개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241131닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241620닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241850닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241539닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241662닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241552닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...