본문 바로가기
Backend/C# .NET

[ASP.NET] Entity Framework Core

by SOLYI 2021. 12. 13.
  • Entity Framework core
  • 데이터 연동방식을 두가지로 제공한다.

1.  Code-First 방식: 코드 작성 우선주의

  마이그레이션 : 미리 작성된 코드로 데이터베이스에 테이블과 컬럼을 생성하는 방식

 

2. Database-First 방식: 데이터베이서 작업 우선주의

  모든 테이블과 컬럼을 데이터베이스에서 테이블과 컬럼을 우선 생성한다.

Entity Data Modeling :  코드를 손쉽게 작성할 수 있도록 도와준다.

 

먼저 Code-First 방식으로 진행해보기로 한다.


Code First 방식

이전 게시글에서 작성한 프로젝트를 열어서 그중 DataModels/User.cs 파일을 열고, 

DataAnnotations 를 추가하고 , 어노테이션을 작성한다.

[Key, StringLength(50), Column(TypeName = "varchar(50)")]  

[Required]

등 아래 소스코드에서 확인

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace NetCore.Data.DataModels
{
    public class User
    {
        [Key, StringLength(50), Column(TypeName = "varchar(50)")]
        public string UserID { get; set;  }
        [Required, StringLength(100), Column(TypeName = "varchar(100)")]
        public string UserName { get; set; }
        ... // 중략
        [Required]
        public DateTime JoinedUtcDate { get; set; }
    }
}

 

그 다음, Service프로젝트에 Data폴더를 생성한 뒤 CodeFirstDbContext.cs 파일을 작성한다.

종속성 - 우클릭 - NuGet 패키지 관리를 선택한 뒤, Microsoft.EntityFrameworkCore 를 설치한다.

 

안정적인 최신버전인 6.0.0 은 설치가 되지않아, 5.0.0 버전으로 설치를 진행하였다.

더보기

심각도 코드 설명 프로젝트 파일 줄 비표시 오류(Suppression) 상태
오류 NU1202 Microsoft.EntityFrameworkCore 6.0.0 패키지가 net5.0(.NETCoreApp,Version=v5.0)과(와) 호환되지 않습니다. Microsoft.EntityFrameworkCore 6.0.0 패키지는 다음을 지원합니다. net6.0(.NETCoreApp,Version=v6.0) NetCore.Services C:\startAspNet\NetCore\NetCore.Services\NetCore.Services.csproj 1

 

그리고 Microsoft.EntityFrameworkCore.SqlServer 또한 추가로 설치를 진행한다.

마찬가지로 위와 유사한 오류가 발생하여 5.0.0 버전으로 진행하였다.

창을 닫은뒤 CodeFirstDbContext.cs 파일로 돌아가 클래스를 : DbContext 로 상속 받는다.

 

더보기

내용을 작성하기 전에 아래 파일 두개를 추가한다!

UserRolesByUser.cs

 UserId, RoleId, OwnedUtcDate  컬럼과 어노데이션 추가!

 이중, UserId와 RoleId는 복합키 이다.

UserRole.cs

  RoleId, RoleName, RolePriority, ModefiedUtcDate  컬럼과 어노테이션 추가

 

내부에서 OnModelCreating 메서드를 상속받아 내용을 채운다.

OnModelCreating 내부에 들어가는 내용은 다음과 같다.

 // 메서드 상속, 부모클래스에서 OnModelCreating 메서드가
    // Virtual 키워드로 지정이 되어있어야만 상속 받을 수 있다.
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
      base.OnModelCreating(modelBuilder);

      //4가지 작업
      // DB 테이블 이름 변경
      modelBuilder.Entity<User>().ToTable(name: "User");

      // 복합Key
      modelBuilder.Entity<UserRolesByUser>().HasKey(c => new { c.UserId, c.RoleId });

      // 기본값 지정
      modelBuilder.Entity<User>(e => { 
        e.Property(c => c.IsMembershipWithdrawn).HasDefaultValue(value: false);
      });

      // 인덱스 지정
      modelBuilder.Entity<User>().HasIndex(c => new { c.UserEmail });
    }

 

순서는 다음과 같다.

 

1. DataAnnotations 설정 - (Data프로젝트 - DataModels/User.cs)

2. FluentAPI 설정 - (Service프로젝트 - Data/CodeFirstDbContext.cs)

3. SQL Server 실행

 

 

 

데이터베이스를 신규로 추가해준다.

 

보안 - 로그인 - 우클릭 - 새 로그인을 선택해서 coreuser / corepw 로 추가해준다.

사용자 맵핑에서 CoreFirstDB 를 체크하여 coreuser, 기본스키마는 dbo. 로 작성후, 아래에서 db_owner도 추가한다.

그 다음 연결을 끊고 다시 연결을 해야하는데 18456 에러가 발생했다. 구글링을 통해 해결 방법을 알 수 있었다.

서버 우클릭 - 속성 - 보안에서 Windows 인증모드가 아닌  SQL Server 및 Windows 인증 모드를 선택해야한다.

 

그럼 다음과 같이 입력시 정상적으로 로그인이 된다!

 

 

 

이제 VS 로 돌아가서 접속정보를 추가해주어야 연결을 할수 있다.

프로젝트의 appsettings.json 파일을 열어서 다음과 같은 접속정보를 추가한다.

  "ConnectionStrings": {
    "DefaultConnection": "Server=서버이름;Database=CodeFirstDB;User Id=coreuser;Password=corepw" //4가지 접속정보
  },
  "Logging": ...

 

강의에서는 지난번과 마찬가지로 Startup.cs 파일에서 서비시스를 추가해주었지만, 나는 그 파일이 존재하지 않으므로 Program.cs에 추가를 진행..............하려 했으나...!!!!!!!

또 강사님의 코드와 버전이 달라서 그런지... Configuration 을 써야하는데 써지지않았다..

40~50분간 찾아 헤매인 결과 ㅠㅠ

스택오버플로우에서 도움되는 글을 찾았다.

https://stackoverflow.com/questions/68980778/config-connection-string-in-net-core-6

builder.Services.AddScoped<IUser, UserService>();  // 이전 시간 진행한 코드 아래에

// program.cs에서 AddDbContext 
builder.Services.AddDbContext<CodeFirstDbContext>(options => {
  options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"),
    sqlServerOptionsAction:mig => mig.MigrationsAssembly(assemblyName:"NetCore.Migrations"));
});

위 코드에서 미리 NetCore.Migrations 를 참조하기 위해 추가해주었고

 

새로운 클래스 라이브러리 프로젝트를를 추가해주었다. NetCore.Migrations

해당 프로젝트에서 종속성 - 우클릭 - NuGet 패키지 관리를 선택한 뒤, Microsoft.EntityFrameworkCore.SqlServer 를 설치한다.

그 후, 종속성 - 우클릭 - 새 참조 추가로 NetCore.Services를 추가해준다.

 

또한 NetCore.Web 프로젝트 - 종속성 - 우클릭 - 새 참조 추가 - NetCore.Migrations를 참조 추가해준다.

 

@@

ForeignKey 설정이 안되어 있어서 User, UserRole, UserRolesByUsers 에 FK 추가를 해주었다.

 

빌드 - 솔루션 다시 빌드 를 눌러 빌드를 해준다 (무슨 의미인지 모르겠다)

 

 

보기 - 다른창 - 패키지 관리자 콘솔 을 켜준다.

명령어 두줄을 작성하여 DB에 테이블과 컬럼을 추가해 줄수 있다.

 add-migration AddingUserTables -project NetCore.Migrations

더보기

https://stackoverflow.com/questions/68980778/config-connection-string-in-net-core-6


PM> add-migration AddingUserTables -project NetCore.Migrations
Build started...
Build succeeded.
No DbContext was found in assembly 'NetCore.Migrations'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.
@@ EntityFrameworkCore.Tools 설치


PM> add-migration AddingUserTables -project NetCore.Migrations
Build started...
Build succeeded.
Your startup project 'NetCore.Web' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.
@@  EntityFrameworkCore.Design 설치


Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.0 initialized 'CodeFirstDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.0' with options: MigrationsAssembly=NetCore.Migrations 
To undo this action, use Remove-Migration.
@@ program.cs 에서 assembly 부분 삭제

Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.0 initialized 'CodeFirstDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.0' with options: None
To undo this action, use Remove-Migration.

 

각종 오류로인해 일단 여기까지...ㅠㅠ

반응형