Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1143. C# - Entity Framework Core 6 개요 [링크 복사], [링크+제목 복사]
조회: 8776
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  [41]  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12604정성태4/18/20217424VS.NET IDE: 163. 비주얼 스튜디오 속성 창의 "Build(빌드)" / "Configuration(구성)"에서의 "활성" 의미
12603정성태4/16/20218305VS.NET IDE: 162. 비주얼 스튜디오 - 상속받은 컨트롤이 디자인 창에서 지원되지 않는 문제
12602정성태4/16/20219515VS.NET IDE: 161. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 [1]
12601정성태4/15/20218600.NET Framework: 1040. C# - REST API 대신 github 클라이언트 라이브러리를 통해 프로그래밍으로 접근
12600정성태4/15/20218784.NET Framework: 1039. C# - Kubeconfig의 token 설정 및 인증서 구성을 자동화하는 프로그램
12599정성태4/14/20219488.NET Framework: 1038. C# - 인증서 및 키 파일로부터 pfx/p12 파일을 생성하는 방법파일 다운로드1
12598정성태4/14/20219603.NET Framework: 1037. openssl의 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법 (2)파일 다운로드1
12597정성태4/13/20219687개발 환경 구성: 569. csproj의 내용을 공통 설정할 수 있는 Directory.Build.targets / Directory.Build.props 파일
12596정성태4/12/20219417개발 환경 구성: 568. Windows의 80 포트 점유를 해제하는 방법
12595정성태4/12/20218845.NET Framework: 1036. SQL 서버 - varbinary 타입에 대한 문자열의 CAST, CONVERT 변환을 C# 코드로 구현
12594정성태4/11/20218300.NET Framework: 1035. C# - kubectl 명령어 또는 REST API 대신 Kubernetes 클라이언트 라이브러리를 통해 프로그래밍으로 접근 [1]파일 다운로드1
12593정성태4/10/20219445개발 환경 구성: 567. Docker Desktop for Windows - kubectl proxy 없이 k8s 대시보드 접근 방법
12592정성태4/10/20219249개발 환경 구성: 566. Docker Desktop for Windows - k8s dashboard의 Kubeconfig 로그인 및 Skip 방법
12591정성태4/9/202112503.NET Framework: 1034. C# - byte 배열을 Hex(16진수) 문자열로 고속 변환하는 방법 [2]파일 다운로드1
12590정성태4/9/20219012.NET Framework: 1033. C# - .NET 4.0 이하에서 Console.IsInputRedirected 구현 [1]
12589정성태4/8/202110343.NET Framework: 1032. C# - Environment.OSVersion의 문제점 및 윈도우 운영체제의 버전을 구하는 다양한 방법 [1]
12588정성태4/7/202110939개발 환경 구성: 565. PowerShell - New-SelfSignedCertificate를 사용해 CA 인증서 생성 및 인증서 서명 방법
12587정성태4/6/202111728개발 환경 구성: 564. Windows 10 - ClickOnce 배포처럼 사용할 수 있는 MSIX 설치 파일 [1]
12586정성태4/5/20219413오류 유형: 710. Windows - Restart-Computer / shutdown 명령어 수행 시 Access is denied(E_ACCESSDENIED)
12585정성태4/5/20219187개발 환경 구성: 563. 기본 생성된 kubeconfig 파일의 내용을 새롭게 생성한 인증서로 구성하는 방법
12584정성태4/1/20219871개발 환경 구성: 562. kubeconfig 파일 없이 kubectl 옵션만으로 실행하는 방법
12583정성태3/29/202111377개발 환경 구성: 561. kubectl 수행 시 다른 k8s 클러스터로 접속하는 방법
12582정성태3/29/202110052오류 유형: 709. Visual C++ - 컴파일 에러 error C2059: syntax error: '__stdcall'
12581정성태3/28/20219990.NET Framework: 1031. WinForm/WPF에서 Console 창을 띄워 출력하는 방법 (2) - Output 디버깅 출력을 AllocConsole로 우회 [2]
12580정성태3/28/20218716오류 유형: 708. SQL Server Management Studio - Execution Timeout Expired.
12579정성태3/28/20218789오류 유형: 707. 중첩 가상화(Nested Virtualization) - The virtual machine could not be started because this platform does not support nested virtualization.
... 31  32  33  34  35  36  37  38  39  40  [41]  42  43  44  45  ...