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)
13306정성태4/3/20233681Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234051Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234399VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233755Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234377Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234466Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234112Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233886Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233868Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234530Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233862Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234146Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234301.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234354오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234475Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234849.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234343.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233529Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233642Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233806Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234248Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233833Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20234057Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233598오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233930Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233858Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...