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)
13600정성태4/18/2024223닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024270닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024281닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024356닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024698닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024823닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024998닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241048닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241202C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241164닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241138닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241149오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241293Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241094Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241149Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241406Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241136닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241627닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241864닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...