Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1143. C# - Entity Framework Core 6 개요 [링크 복사], [링크+제목 복사]
조회: 8653
글쓴 사람
정성태 (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)
13528정성태1/14/20242033Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241960오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242051닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242021오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242066오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241889오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242030닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242110닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241858오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241939닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242174닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242017스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242104닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242376닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242065개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242006닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20241979개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20241997닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241937닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241966오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242016오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242701닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232191닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232707닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232322닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232191Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...