이야기를 나눠요
130만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
데이터 분석 SQL Fundamentals
SQL Error [42501]: ERROR: permission denied for database postgres
안녕하세요 '실습용 스키마 설치 이슈 시 적용하세요'라는 강의편에 맥북에서 create schema nw; 이렇게 DBeaver에서 실행을 하면 아래와 같은 에라가 뜨네요 ㅠ SQL Error [42501]: ERROR: permission denied for database postgres
-
다양한 사례로 익히는 SQL 데이터 분석
버전을 맞추었는데도 오류가 발생합니다. (pd ver: 2.0.3, sqlalchemy: 2.0.0)
query = """ select * from nw.customers """ df = pd.read_sql_query(sql=query, con=postgres_engine) df.head(10) --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) Cell In[25], line 4 1 query = """ 2 select * from nw.customers 3 """ ----> 4 df = pd.read_sql_query(sql=query, con=postgres_engine) 5 df.head(10) File ~\anaconda3\Lib\site-packages\pandas\io\sql.py:468, in read_sql_query(sql, con, index_col, coerce_float, params, parse_dates, chunksize, dtype, dtype_backend) 465 if dtype_backend is lib.no_default: 466 dtype_backend = "numpy" # type: ignore[assignment] --> 468 with pandasSQL_builder(con) as pandas_sql: 469 return pandas_sql.read_query( 470 sql, 471 index_col=index_col, (...) 477 dtype_backend=dtype_backend, 478 ) File ~\anaconda3\Lib\site-packages\pandas\io\sql.py:832, in pandasSQL_builder(con, schema, need_transaction) 829 raise ImportError("Using URI string without sqlalchemy installed.") 831 if sqlalchemy is not None and isinstance(con, (str, sqlalchemy.engine.Connectable)): --> 832 return SQLDatabase(con, schema, need_transaction) 834 warnings.warn( 835 "pandas only supports SQLAlchemy connectable (engine/connection) or " 836 "database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 " (...) 839 stacklevel=find_stack_level(), 840 ) 841 return SQLiteDatabase(con) File ~\anaconda3\Lib\site-packages\pandas\io\sql.py:1539, in SQLDatabase.__init__(self, con, schema, need_transaction) 1537 self.exit_stack.callback(con.dispose) 1538 if isinstance(con, Engine): -> 1539 con = self.exit_stack.enter_context(con.connect()) 1540 if need_transaction and not con.in_transaction(): 1541 self.exit_stack.enter_context(con.begin()) File ~\anaconda3\Lib\site-packages\sqlalchemy\engine\base.py:3245, in Engine.connect(self) 3222 def connect(self) -> Connection: 3223 """Return a new :class:`_engine.Connection` object. 3224 3225 The :class:`_engine.Connection` acts as a Python context manager, so (...) 3242 3243 """ -> 3245 return self._connection_cls(self) File ~\anaconda3\Lib\site-packages\sqlalchemy\engine\base.py:145, in Connection.__init__(self, engine, connection, _has_events, _allow_revalidate, _allow_autobegin) 143 if connection is None: 144 try: --> 145 self._dbapi_connection = engine.raw_connection() 146 except dialect.loaded_dbapi.Error as err: 147 Connection._handle_dbapi_exception_noconnection( 148 err, dialect, engine 149 ) File ~\anaconda3\Lib\site-packages\sqlalchemy\engine\base.py:3269, in Engine.raw_connection(self) 3247 def raw_connection(self) -> PoolProxiedConnection: 3248 """Return a "raw" DBAPI connection from the connection pool. 3249 3250 The returned object is a proxied version of the DBAPI (...) 3267 3268 """ -> 3269 return self.pool.connect() File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\base.py:452, in Pool.connect(self) 444 def connect(self) -> PoolProxiedConnection: 445 """Return a DBAPI connection from the pool. 446 447 The connection is instrumented such that when its (...) 450 451 """ --> 452 return _ConnectionFairy._checkout(self) File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\base.py:1255, in _ConnectionFairy._checkout(cls, pool, threadconns, fairy) 1247 @classmethod 1248 def _checkout( 1249 cls, (...) 1252 fairy: Optional[_ConnectionFairy] = None, 1253 ) -> _ConnectionFairy: 1254 if not fairy: -> 1255 fairy = _ConnectionRecord.checkout(pool) 1257 if threadconns is not None: 1258 threadconns.current = weakref.ref(fairy) File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\base.py:716, in _ConnectionRecord.checkout(cls, pool) 714 rec = cast(_ConnectionRecord, pool._do_get()) 715 else: --> 716 rec = pool._do_get() 718 try: 719 dbapi_connection = rec.get_connection() File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\impl.py:168, in QueuePool._do_get(self) 166 return self._create_connection() 167 except: --> 168 with util.safe_reraise(): 169 self._dec_overflow() 170 raise File ~\anaconda3\Lib\site-packages\sqlalchemy\util\langhelpers.py:147, in safe_reraise.__exit__(self, type_, value, traceback) 145 assert exc_value is not None 146 self._exc_info = None # remove potential circular references --> 147 raise exc_value.with_traceback(exc_tb) 148 else: 149 self._exc_info = None # remove potential circular references File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\impl.py:166, in QueuePool._do_get(self) 164 if self._inc_overflow(): 165 try: --> 166 return self._create_connection() 167 except: 168 with util.safe_reraise(): File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\base.py:393, in Pool._create_connection(self) 390 def _create_connection(self) -> ConnectionPoolEntry: 391 """Called by subclasses to create a new ConnectionRecord.""" --> 393 return _ConnectionRecord(self) File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\base.py:678, in _ConnectionRecord.__init__(self, pool, connect) 676 self.__pool = pool 677 if connect: --> 678 self.__connect() 679 self.finalize_callback = deque() File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\base.py:902, in _ConnectionRecord.__connect(self) 900 self.fresh = True 901 except BaseException as e: --> 902 with util.safe_reraise(): 903 pool.logger.debug("Error on connect(): %s", e) 904 else: 905 # in SQLAlchemy 1.4 the first_connect event is not used by 906 # the engine, so this will usually not be set File ~\anaconda3\Lib\site-packages\sqlalchemy\util\langhelpers.py:147, in safe_reraise.__exit__(self, type_, value, traceback) 145 assert exc_value is not None 146 self._exc_info = None # remove potential circular references --> 147 raise exc_value.with_traceback(exc_tb) 148 else: 149 self._exc_info = None # remove potential circular references File ~\anaconda3\Lib\site-packages\sqlalchemy\pool\base.py:898, in _ConnectionRecord.__connect(self) 896 try: 897 self.starttime = time.time() --> 898 self.dbapi_connection = connection = pool._invoke_creator(self) 899 pool.logger.debug("Created new connection %r", connection) 900 self.fresh = True File ~\anaconda3\Lib\site-packages\sqlalchemy\engine\create.py:640, in create_engine.<locals>.connect(connection_record) 638 if connection is not None: 639 return connection --> 640 return dialect.connect(*cargs, **cparams) File ~\anaconda3\Lib\site-packages\sqlalchemy\engine\default.py:580, in DefaultDialect.connect(self, *cargs, **cparams) 578 def connect(self, *cargs, **cparams): 579 # inherits the docstring from interfaces.Dialect.connect --> 580 return self.loaded_dbapi.connect(*cargs, **cparams) File ~\anaconda3\Lib\site-packages\psycopg2\__init__.py:122, in connect(dsn, connection_factory, cursor_factory, **kwargs) 119 kwasync['async_'] = kwargs.pop('async_') 121 dsn = _ext.make_dsn(dsn, **kwargs) --> 122 conn = _connect(dsn, connection_factory=connection_factory, **kwasync) 123 if cursor_factory is not None: 124 conn.cursor_factory = cursor_factory UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 63: invalid start byte 판다스 버전과 sqlalchemy 버전은 다음과 같이 맞추었습니다2.0.3 2.0.0
-
따라하며 배우는 NestJS
[해결]EntityMetadataNotFoundError: No metadata for "BoardRepository" was found
왠만하면 최신버전으로 진행하느라 @nestjs/typeorm@10.0.0 typeorm@0.3.x로 진행중에 만난 오류입니다. 해당 강좌 커뮤니티에 검색해보면 나오지만,typeorm의 버전이 0.2.x와 0.3.x의 사용법 차이로 생기는 문제입니다. --해결법--npm i typeorm@0.2.45를 통해 typeorm의 버전을 낮춰 줍니다.(@nest/typeorm은 그냥 높은 버전 썼습니다) board.service.ts1-1 constructor( @InjectRepository(BoardRepository) private boardRepository:BoardRepository ){}-> InjectRepository를 Repository에서 Entity로 변경 constructor( @InjectRepository(Board) private boardRepository:BoardRepository ){} 1-2const found = await this.boardRepository.findOneBy({id})->typeorm0.3의 문법을 0.2의 문법으로 변경const found = await this.boardRepository.findOne(id) board.module.ts@Module({ imports: [ TypeOrmModule.forFeature([BoardRepository]) ], controllers: [BoardsController], providers: [BoardsService] })->forFeature()의 Repository를 Entity로 변경@Module({ imports: [ TypeOrmModule.forFeature([Board]) ], controllers: [BoardsController], providers: [BoardsService] }) 이렇게 변경하면 잘 되는거 같습니다. 이대로 강의 진행해보고 typeorm0.3 진행해봐야겠네요~
-
데이터 분석 SQL Fundamentals
sql 이후 머신러닝을 배우려 합니다.
이왕이면 강사님께서 올리신 강좌를 구매해이어서 학습을 해보려 합니다.로드맵이 있다면, 보고 구매를 하려고 했는데 올려져 있는 강의 수는 많은데 머신러닝 관련 로드맵이 없더라고요 파이썬 머신러닝 완벽 가이드,딥러닝 컴퓨터 비전 완벽 가이드딥러닝 CNN 완벽 가이드캐글 advanced 머신러닝 실전 박치기이 강의들을 기본부터 학습하려 하는데요오래된 강좌가 개정되어 다른 이름으로 만들어져 있어서내용이 겹치는게 있는지아니면 모두 수강하는게 맞는지 어떤 순서로 학습하면 되는지 알고 싶습니다.
-
데이터 분석 SQL Fundamentals
With 문
강사님 안녕하세요,조인실습2에서 부서명 SALES와 RESEARCH 소속 직원별로 과거부터 현재까지 모든 급여를 취합한 평균 급여 예시가 조금 헷갈립니다. With 문이 서브쿼리 역할을 하는걸로 이해하고 있는데 해당 예시에서 왜 with문이 왜 필요한지, with문 또는 서브쿼리 사용하지 않고 쿼리를 진행시키는 방법이 있는지 궁금합니다ㅠ
-
하루만에 배우는 express with AWS
[강의 추가] 건의
삭제된 글입니다
-
다양한 사례로 익히는 SQL 데이터 분석
나래비는 일본어 입니다..
선생님.. 나래비는 일본어 입니다. 어감이 예뻐서 옛 우리말인줄 알고 찾아봤는데 '줄을 세우다'라는 일본어 '나라비'가 어원이라고 하네요
-
따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
context-api쪽 auth.tsx를 제 나름대로 리팩토리 해보았습니다.
[auth.tsx]import { User } from '@/shared/interfaces/user.interface'; import { createContext, FC, PropsWithChildren, useContext, useReducer, Dispatch, ReactNode, } from 'react'; interface AuthState { authenticated: boolean; user: User | undefined; loading: boolean; } export type AuthAction = | { type: 'LOGIN'; payload: User } | { type: 'LOGOUT' } | { type: 'STOP_LOADING' } | { type: undefined }; const initialState: AuthState = { authenticated: false, user: undefined, loading: true, }; const AuthContext = createContext<{ state: AuthState; dispatch: Dispatch<AuthAction>; }>({ state: initialState, dispatch: () => null, }); const authReducer = (state: AuthState, action: AuthAction): AuthState => { switch (action.type) { case 'LOGIN': return { ...state, authenticated: true, user: action.payload, }; case 'LOGOUT': return { ...state, authenticated: false, user: undefined, }; case 'STOP_LOADING': return { ...state, loading: false, }; default: throw new Error(`Unknown action type: ${action.type}`); } }; const AuthProvider: FC<PropsWithChildren<{ children?: ReactNode }>> = ({ children, }) => { const [state, dispatch] = useReducer(authReducer, initialState); return ( <AuthContext.Provider value={{ state, dispatch }}> {children} </AuthContext.Provider> ); }; const useAuthStateDispatch = () => useContext(AuthContext); export { AuthProvider, useAuthStateDispatch }; [login.tsx]import InputGroup from '@/components/ui/field/InputGroup'; import axios from 'axios'; import { AuthAction, useAuthStateDispatch } from 'context/auth'; import { NextPage } from 'next'; import Link from 'next/link'; import { useRouter } from 'next/router'; import React, { FormEvent, useState } from 'react'; const LoginPage: NextPage = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [errors, setErros] = useState<any>({}); const router = useRouter(); const { dispatch } = useAuthStateDispatch(); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); try { const res = await axios.post( '/auth/login', { password, username }, { withCredentials: true }, ); dispatch({ type: 'LOGIN', payload: res.data?.user }); router.push('/'); } catch (error: any) { console.log(error); setErros(error.response.data || {}); } }; return ( <div className="bg-white"> <div className="flex flex-col items-center justify-center h-screen p-6"> <div className="w-10/12 mx-auto md:w-96"> <h1 className="mb-2 text-lg font-medium">로그인</h1> <form onSubmit={handleSubmit}> <InputGroup placeholder="Username" value={username} setValue={setUsername} error={errors.username} /> <InputGroup placeholder="Password" value={password} setValue={setPassword} error={errors.password} /> <button className="w-full py-2 mb-1 text-xs font-bold text-white uppercase bg-gray-400 border border-gray-400 rounded"> 로그인 </button> </form> <small> 아직 아이디가 없나요? <Link href="/register" className="ml-1 text-blue-500 uppercase"> 회원가입 </Link> </small> </div> </div> </div> ); }; export default LoginPage; 누군가에겐 도움이 되지 않을까해서 남겨 보아요!
-
데이터 분석 SQL Fundamentals
datagrip에서 복구하기
datagrip에서 복구 하려고 하면 postgre 관련 cli 가 필요합니다. 아래와 같이 우선 실행$ brew install libpq $ echo 'export PATH="/opt/homebrew/opt/libpq/bin:$PATH"' >> ~/.zshrc $ source ~/.zshrc $ psql --version psql (PostgreSQL) 15.2Path to pg_restore 에서 CMD+SHIFT+G 눌러서 brew로 설치한 디렉토리로 이동이후 복구 하면 됩니다
-
Prisma로 알아보는 postgreSQL와 mongoDB
따라쳐야할 곳들이 너무 빨리 지나갑니다.
안녕하세요.강의를 보면서 중간중간 따라쳐야 할 곳들이 너무 빠르게 지나가서 방향키와 스페이스를 이용해서 그 부분을 딱 맞춰서 멈추고 따라치기가 힘든 경우가 계속 발생하네요. 이점 감안하셔서 따라 쳐야할 곳에 표기 + 잠깐의 지연 타임 정도로 영상 수정하시면 이후 수강자들이 많이 편해질듯싶습니다.좋은 강의 감사합니다.
-
스프링 DB 1편 - 데이터 접근 핵심 원리
토이 프로젝트 DB 선정 중 궁금한 점이 있습니다!
안녕하세요!벌써 무더운 날씨가 지나고 쌀쌀한 날씨가 찾아오고 있는 요즘입니다.면역력이 떨어지는 환절기 조심하시고 건강한 연말을 준비하셨으면 좋겠다는 말씀 드리면서해당 글을 쓰게 된 계기와 함께 궁금증에 대한 내용을 조심스레 작성해보겠습니다.현재 대략 3명 정도의 인력(백엔드+기획 / 프론트 / 기획+디자인)으로 토이 프로젝트를 진행하고 있습니다.서비스의 개요는 특정 카테고리&내가 원하는 기준에 해당하는 "내주변"식당의 위치를 조회하는 서비스 + 여러 조건에 대해 실시간으로 선택하며 달라지는 결과들을 확인하는 서비스를 기획하고 있습니다.향후 예약 기능도 추가할 계획도 하고 있구요,서비스의 전체적 느낌은 네이버 지도 + 망고플레이트 + 테이블링 정도 입니다.조회가 많고 다양한 쿼리문이 나올 것 같고지역/지리 정보를 빈번하게 사용할 것 같아 MySQL이 아닌 PostgreSQL에 관심이 생기기 시작했고자연스레 많은 고민과 궁금증이 생기게 되어 이렇게 찾아와 질문드리게 되었습니다.이에 대한 주요 질문의 내용은 아래와 같습니다.[PostgreSQL을 고려하는 이유]참고 : https://techblog.woowahan.com/6550/ 많은 양의 지역정보(행정동 경계 및 구역)를 빈번하게 사용할 예정 -> 데이터 타입(geometry) 이 적절하고 조회 작업이 많은 면에서 효율적일 것이라고 생각PostGIS를 사용해보고 싶습니다. (현재 erd 작성에 사용하고 있는 예시 : https://www.erdcloud.com/d/2mDmcrHWY3CqW4Rrp ) PostgreREST 라이브러리로 REST 방식 사용 가능 -> 오픈 API다양한 객체 타입으로 데이터 조회하는 기능이 많은 서비스여러가지 조건(복잡한 쿼리 예상)을 적용할 검색 조회 서비스 [고민하는 이유]오픈 API를 많이 사용할 예정( 소셜로그인 , 행정동 경계, 소셜 공유, 지도 등) 인데 공식 문서에서는 보통 REST API 방식의 사용법만 찾을 수 있음.부족한 개인 역량..(MySQL만 사용한 적이 있습니다..) -> 충분한 학습없이 시간낭비 할 가능성이 높은데 혼자만 진행하는 프로젝트가 아닌 팀원들이 함께 진행하는 프로젝트여서 더욱 고민이 됩니다. [찾아본 결과(확실하진.. 않습니다ㅠ)]MyBatis & Master-Slave 형식으로 각각의 Configuration 및 properties 관리를 통해 다중 db 사용DB Link를 활용하여 원격으로 서로 다른 table의 정보를 받아와서 사용하는 방법하지만 보통 MySQL과 Maria를 연결(DB 특성이 유사)의 예시만 찾아볼 수 있었고대부분 PostSQL로 이관하는 내용이 가장 많았습니다.생각했던 것 처럼 보안이나 운용 측면에서 관리하기 어려움이 있는 요소이다 보니레퍼런스도 많지 않아 위와 같이 확실하지 않은 방법으로 유추하고 있습니다. 사실 프로젝트 규모나 서비스 기능 복잡도 측면에서는 이렇게까지 번거롭게 하지 않고하나의 DB(MySQL)로도 충분히 작동하는데 문제 없겠지만서비스에 조금 더 최적화된 DB라고 생각되기도 하고 경험해보고 싶은 마음에 이런 고민을 하고 있습니다.혹시나 현업에서도 여러 DB를 한 서비스에서 사용하는 경우가 많은지많다면 효율성 증진이나 개선된 사항으로 어떤 점 들이 있는지, 어떤 방식으로 연결하는지 궁금합니다 ㅠㅜㅜ 너무나도 부족한 역량과 지식을 기반으로 허술한 질문을 드려 죄송합니다..!!직접적인 해결방법이 아니더라도 선생님께서 생각하시는 어떤 것이든 전달해주시면적극적으로 습득하고 활용해보겠습니다..!!감사합니다.
-
해외취업 ASP.NET Core 웹개발 기본 강좌
VS mac, .Net Core 3.1, PostgreSQL
- 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 안녕하세요. 자바개발자인데 5월부터 시작하는 .Net Core 프로젝트때문에 공부좀 할려고 강의를 듣게되었습니다. 하지만 .Net Core는 처음이고 .Net Core에대한 지식조차 하나도 없는데... DB관련에서 어려움이 생기더군요.혹시나 같은 어려움을 겪으시는 분이 있으시다면 참조하세요. ●윈도우 사용자분들은 섹션 4. 엔티티 프레임워크 코어의 DbContext 강의에서 아래 명령어 실행후 하시고① ...MyApp> dotnet tool install --global dotnet-ef② ..MyApp> dotnet add package Microsoft.EntityFrameworkCore.Design③ ..MyApp> dotnet ef <- 이젠 강의와 같은 정보가 출력된 것을 볼 수가 있습니다. 아래 MyAppContext.cs 내용이 있으니 참조하세요. MyAppContext설정하나가 추가됨 섹션 6. ASP.NET Core Identity 의 환경설정에서 DbContext에서 IdentityDbContext<ApplicationUser>로 변경하면 IdentityDbContext가 임포드할 수가 없다. 프로젝트폴더(MyApp) 우클릭 > [프로젝트 파일 편집] 클릭 MyApp.proj:다른건 디폴트로 건들리지 말아 주시고 PostgreSQL 라이브러리만 추가 <ItemGroup> ⓪<!-- dotnet add package Microsoft.EntityFrameworkCore.Design 인스톨후 자동추가됨 --> ⓪<!-- http://www.npgsql.org/efcore/index.html --> ⓪<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.5"> ⓪⓪<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> ⓪<PrivateAssets>all</PrivateAssets> ⓪</PackageReference><!-- 추가 -->④<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" /></ItemGroup>① ~ ④까지만 하시면 .Net Core 3.1로 하셔도 문제없으리라 봅니다. ● 환경 맥 OS 카탈리나 .Net Core 3.1 현재 3.1만 다운로드? 2.0은 어디있는 것인지 모르겠슴. .Net 5.0Visual Studio macDockerPostgreSQL 11.5 ● wwwroot는 직접생성 ● Controllers 폴더에 HomeController.cs 생성하기. 추가 -> 새 파일 -> ASP .Net Core -> 컨트롤러 클래스 -> 파일명 : HomeController ● Model 작성 추가 -> 새 파일 -> General -> 빈 클래스 -> 파일명 : Student or 추가 -> 새 클래스 -> General -> 빈 클래스 -> 파일명 : Student ● Razor 뷰 파일 생성.(Index.cshtml) 추가 -> 새 파일 -> ASP .Net Core -> Razor 뷰[cshtml] -> 파일명 : Index(Index -> Student ● Startup.cs : MVC 패턴에 매핑을위한 세팅 /* .Net Core 2.1 app.UseMvc(routes => { ⓪routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); */ // ASP.NET Core 3.1 app.UseEndpoints(endpoints => { ⓪endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); % dotnet ef <- EF Core 3.0부터 dotnet ef 컨맨드가 .NET SDK에 포함되어 있지 않다합니다. ● 터미널에서 열기 1.[프로젝트(MyApp)] 우클릭 > [도구] > [Open in Terminai Window] 2. 또는 [프로젝트(MyApp)] 우클릭 > [도구] > [터미널에서 열기] ● % dotnet ef <- 없데요. Could not execute because the specified command or file was not found. Possible reasons for this include: *You misspelled a built -in dotnet command. *You intended to execute a.NET program, but dotnet - ef does not exist. *You intended to run a global tool, but a dotnet - prefixed executable with this name could not be found on the PATH. 1이나 2의 [터미널에서 열기]해서 아래와 같이 인스톨 또는 업데이트해준다. 처음이면 인스톨. ● % dotnet tool install --global dotnet-ef 없으면 인스톨 % dotnet tool update --global dotnet-ef 버젼이 낮으면 업데이트(3.0.0이상으로.) ● % dotnet add package Microsoft.EntityFrameworkCore.Design <- 이것도 설치해야함. ● % dotnet ef <- 이젠 강의와 같은 정보가 출력된 것을 볼 수가 있습니다. ● view > sql server object explorer <- visual studio mac 에는 설치가 안되는 듯. Docker에 리눅스 이미지가 있다하는데, 저는 이 번 프로젝트가 Oracle에서 PostgreSQL로 마이그레이션이라 PostgreSQL로. PostgreSQL은 Docker에 설치하셔도 되고, 직접 로컬에 설치하셔도 됩나다. ● Docker를 설치하고 MyApp/docker-compose.yml 생성 ● appsetting(마이그레이션을 위해 appsetting생성) 추가 -> 새 파일 -> ASP .Net Core -> 앱 설정 파일(App Settings File) > 파일명 : appsettings 디폴트 Docker의 DB실행 MyApp 디렉토리로 이동. VS mac 터미널로 여시길. ● % docker-compose up -d -d는 백그라운드로 실행(도커의 PostgreSQL 시작) ● % docker-compose down 백그라운드 종료(PostgreSQL 종료). 도커 어플리케이션에서 종료해도 됨. 여기까지 진행하시면 강의 따라가실 수 있으십니다. 현재 섹션 5. Repository 패턴까지는 문제없네요. ### 생성된 파일 첨부 ● MyApp/appsettings.json <- 생성 추가 -> 새 파일 -> ASP .Net Core -> 앱 설정 파일(App Settings File) > 파일명 : appsettings 디폴트 { ⓪"Logging": {⓪⓪"LogLevel": {⓪⓪⓪"Default": "Warning"⓪⓪} ⓪}, ⓪"AllowedHosts": "*", <- 콤마부터 추가 ⓪"ConnectionStrings": {⓪⓪"MyAppContext": "Host=localhost;Database=MyApp;Port=15432;Username=cstest;Password=cstest"⓪} } ● MyApp/docker-compose.yml <- 생성 version: '3' volumes: ⓪postgres_data: ⓪⓪driver: 'local' services: ⓪postgres: ⓪⓪build: ⓪⓪⓪context: ./postgres ⓪⓪⓪dockerfile: Dockerfile⓪⓪container_name: "postgres1152" # Docker 컨테이너명⓪⓪environment: ⓪⓪⓪POSTGRES_PASSWORD: postgres # 수퍼유저 패스워드 ⓪⓪⓪POSTGRES_USER: cstest # 추가할 DB유저ID ⓪⓪⓪POSTGRES_PASSWORD: cstest # DB유저패스 ⓪⓪⓪POSTGRES_DB: MyApp # DB명 ⓪⓪⓪TZ: "Asia/Tokyo" ⓪⓪ports: - 15432:5432 # Docker:Docker내부의 PostgreSQL port ⓪⓪volumes: ⓪⓪⓪- postgres_data:/var/lib/postgresql/data ⓪⓪⓪- ./postgres/sql:/docker-entrypoint-initdb.d ● MyApp/postgres/Dockerfile <- 생성FROM postgres:11.5-alpine <- 버젼은 원하는 버젼으로. ● MyApp/Startup.cspublic void ConfigureServices(IServiceCollection services) {services.AddDbContext<MyAppContext>(options => {⓪// PostgreSQL⓪options.UseNpgsql(_config.GetConnectionString("MyAppContext")); }); ● 프로젝트폴더(MyApp) 우클릭 > [프로젝트 파일 편집] 클릭 MyApp.proj:다른건 디폴트로 건들리지 말아 주시고 PostgreSQL 라이브러리만 추가 <ItemGroup> ⓪<!-- dotnet add package Microsoft.EntityFrameworkCore.Design 인스톨후 자동추가됨 --> ⓪<!-- http://www.npgsql.org/efcore/index.html --> ⓪<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.5"> ⓪⓪<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> ⓪<PrivateAssets>all</PrivateAssets> ⓪</PackageReference>⓪<!-- PostgreSQL 라이브러리 추가입력 --> ⓪<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.5.1" /> </ItemGroup> ● MyAppContext.cs생성자의 매개변수 DbContextOptions에 MyAppContext추가public class MyAppContext : DbContext { ⓪public MyAppContext(DbContextOptions<MyAppContext > options) : base(options){} ⓪public DbSet<Student> Students { get; set; } ⓪public DbSet<Teacher> Teachers { get; set; }} 추가기입 섹션 6. ASP.NET Core Identity 의 환경설정에서 DbContext에서 IdentityDbContext<ApplicationUser>로 변경하면 IdentityDbContext가 임포드할 수가 없네요.● 프로젝트폴더(MyApp) 우클릭 > [프로젝트 파일 편집] 클릭 MyApp.proj:다른건 디폴트로 건들리지 말아 주시고 Identity 라이브러리만 추가 <ItemGroup> ⓪<!-- dotnet add package Microsoft.EntityFrameworkCore.Design 인스톨후 자동추가됨 --> ⓪<!-- http://www.npgsql.org/efcore/index.html --> ⓪<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.5"> ⓪⓪<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> ⓪<PrivateAssets>all</PrivateAssets> ⓪</PackageReference>⓪<!-- PostgreSQL 라이브러리 추가입력 --> ⓪<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.5.1" /> <!-- 추가 --><PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" /></ItemGroup>