Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1143. C# - Entity Framework Core 6 개요 [링크 복사], [링크+제목 복사]
조회: 8630
글쓴 사람
정성태 (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)
13501정성태12/25/20232087개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232178디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20232824닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232294오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232310Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232319Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232501Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232559닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232262개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232232Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232345개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232133개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232067오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232381개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232195개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232088오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232162개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232298닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232821닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232267개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232608개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232302개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232483닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232207닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232279닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...