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)
13535정성태1/22/20242432닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242250닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242463닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242354닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242247닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242201닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242059닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242183Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242128오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242213닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242163오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242227오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242034오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242199닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242264닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242006오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242097닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242363닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242203스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242315닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242591닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242264개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242189닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242154개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242176닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242107닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...