Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Entity Framework 4.1의 Code First를 이용한 SQL Azure 데이터베이스 생성


제가 모르는 걸 수도 있는데, 현재 SQL Azure 데이터베이스에 테이블을 생성하는 가장 쉬운 방법이 SSMS(SQL Server Management Service)를 이용하여 "테이블 생성 스크립트를 직접 실행"하는 방법입니다. 사실, 개발이 진행되다 보면 DB 생성 스크립트 문 유지하는 것도 일인데요.

그러지 말고, ^^ (Linq to SQL이나) Entity Framework 의 자동 DB 생성을 이용해 보면 어떨까요?

그동안 Linq to SQL에 부러운 것이 있었다면 바로 Code-first 기능이었는데, 이번 EF 4.1 부터는 다행히 이 기능이 추가되어서 적어도 SQL 서버가 대상이라면 EF 4.1 만한 도구가 없을 것 같습니다.

아쉬운 점이라면 Visual Studio 2010에 기본적으로 포함되어 있지 않아서 별도로 다음의 경로에서 다운로드 받아서 설치를 해야 합니다.

Get Started Developing with the ADO.NET Entity Framework
; https://learn.microsoft.com/en-us/ef/ef6/fundamentals/install

EntityFramework
; https://www.nuget.org/packages/EntityFramework/

Code-First 관련해서 생소한 분들은 다음의 글을 5분만 짬을 내서 읽어보시면 금방 이해하실 수 있을 것입니다.

Tutorial: Get Started with Entity Framework 6 Code First using MVC 5
; https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

간단하게 실습을 한번 해볼까요? 이를 위해 다음의 책에 나오는, 무지 간단한 노트패드 예제를 해보겠습니다.

Beginning Windows Phone 7 Development
; http://www.yes24.com/24/goods/5177819

우선, DB 테이블에 매핑될 개체를 만들고,

public class Note
{
    public Guid NoteId { get; set; }
    public Guid UserId { get; set; }
    public string NoteText { get; set; }
    public string Description { get; set; }

    public User User { get; set; }
}

public class User
{
    public Guid UserId { get; set; }
    public string Name { get; set; }
}

이제 EF 기능을 넣기 위해, Entity Framework 4.1 라이브러리와 기존의 System.Data.Entity 어셈블리를 참조 추가합니다.

codefirst_with_azure_1.png

codefirst_with_azure_2.png

다음으로, DataContext를 만들어 주어야겠지요.

public class NotepadDataContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Note> Notes { get; set; }
}

마지막으로 app.config에 (일단 Azure보다는 로컬에 테스트를 하는) 연결 문자열을 지정해 주고,

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add
      name="NotepadDataContext"
      providerName="System.Data.SqlClient"
      connectionString="Server=.;Database=NotepadDB;Trusted_Connection=true;"/>
  </connectionStrings>
</configuration>

이제 다음과 같이 코드를 실행하면 완료!

static void Main(string[] args)
{
    using (var db = new NotepadDataContext())
    {
        db.Database.CreateIfNotExists();
    }
}

모든 것을 기본값으로 둔 상태에서 각각의 필드들은 아래와 같은 DB 타입들로 매핑되어 데이터베이스가 생성됩니다.

User 타입
.UserId == PK, uniqueidentifier, not null
.Name == nvarchar(max), null

Note 타입
.NoteId == PK, uniqueidentifier, not null
.UserId == FK, uniqueidentifier, not null
.NoteText == nvarchar(max), null
.Description == nvarchar(max), null

아쉽게도 현재 정의된 필드 형식은 책에 있는 것과 약간 다릅니다. 예를 들어, Name필드의 경우 nvarchar(max)가 아니라 nvarchar(50) 인데 이런 부분에 대해 조정해 줄 필요가 있습니다. 물론 어렵지 않습니다. 간단하게 특성을 지정해서 우리가 원하는 데로 사용자 정의하는 것이 가능한데, 이를 위해서는 "System.ComponentModel.DataAnnotations" 어셈블리를 추가로 참조해야 합니다.

이렇게 해서, 적어도 책에 있는 간단한 예제에 (int identity만 제외하고) 부합하는 DB를 생성하려면 다음과 같은 Entity 정의로 완료될 수 있습니다. (저같은 개발자에게는 테이블 생성 SQL 스크립트 보다 아래의 코드가 훨씬 더 쉽습니다.)

public class User
{
    public Guid UserId { get; set; }

    [StringLength(50)]
    public string Name { get; set; }
}

public class Note
{
    public Guid NoteId { get; set; }
    public Guid UserId { get; set; }
    public string NoteText { get; set; }
    [StringLength(50)]
    public string Description { get; set; }

    public User User { get; set; }
}

자, 이제 Sql Azure에 테스트를 해볼까요? ^^ 위의 상태에서 단순히 연결문자열만 변경해 주면 끝입니다.

Password={암호};Persist Security Info=True;User ID={계정};Initial Catalog=NotepadDB;Data Source={SQL Azure서버}.database.windows.net


실행해 보면, ... 다음과 같이 SQL Azure에 DB 가 구성되어 있습니다. 멋지죠? ^^

codefirst_with_azure_3.png

첨부된 파일은 위의 예제 코드를 담고 있습니다.








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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/23/2023]

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

비밀번호

댓글 작성자
 



2011-06-20 09시24분
[김기원] 이보다 더 쉽게 코드를 짤 수 있을 까요?
만약 그렇다면 개발자는 밥먹고 살기 힘들지 않을까요? ^^
[guest]
2011-06-20 12시10분
분명히 편해지고 있는 것 같긴 한데, 이상하게 왜 갈수록 더 공부를 해야하는 걸까요? ^^;
정성태
2021-05-24 02시06분
How to Build an Event-Driven ASP.NET Core Microservice Architecture with RabbitMQ and Entity Framework
; https://dev.to/christianzink/how-to-build-an-event-driven-asp-net-core-microservice-architecture-4fnh

------------------

EF Core database model first - take it to the next level with Power Tools CLI | .NET Conf 2023
; https://www.youtube.com/watch?v=fwR59ep-2-8

c:\temp> dotnet tool install --global ErkEJ.EFCorePowerTools.Cli --version 8.0.*-*

c:\temp> efcpt --help
c:\temp> efcpt "...connection string..." mssql
정성태

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/20232631닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232488닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232420닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232729Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232460닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232517개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232325개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232658닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232355Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232865닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232466닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232663닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232903닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232834닷넷: 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/20232724스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232616닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232871닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232929닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233111닷넷: 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  ...