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
정성태

... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
12931정성태1/20/20226413개발 환경 구성: 632. ASP.NET Core 프로젝트를 AKS/k8s에 올리는 과정
12930정성태1/19/20227054개발 환경 구성: 631. AKS/k8s의 Volume에 파일 복사하는 방법
12929정성태1/19/20226856개발 환경 구성: 630. AKS/k8s의 Pod에 Volume 연결하는 방법
12928정성태1/18/20227001개발 환경 구성: 629. AKS/Kubernetes에서 호스팅 중인 pod에 shell(/bin/bash)로 진입하는 방법
12927정성태1/18/20226757개발 환경 구성: 628. AKS 환경에 응용 프로그램 배포 방법
12926정성태1/17/20227247오류 유형: 787. AKS - pod 배포 시 ErrImagePull/ImagePullBackOff 오류
12925정성태1/17/20227350개발 환경 구성: 627. AKS의 준비 단계 - ACR(Azure Container Registry)에 docker 이미지 배포
12924정성태1/15/20228829.NET Framework: 1134. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) [2]파일 다운로드1
12923정성태1/15/20227758개발 환경 구성: 626. ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
12922정성태1/14/20226807개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225779개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226538오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226354Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226592Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225800오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225529오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225807오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227765VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228283.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228917개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226223VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226718제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20228104오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225951.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226421오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20227067.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...