(해당 포스팅은 이전 포스팅과 이어지는 글입니다.)
이번 포스팅에서는 EntityFramework를 이용하여 DB에 Insert, Update, Delete 를 적용하는 방법에 대해 알아보도록 하겠습니다.
현재 DB상황은 아래와 같습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework DB상황](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
1) Insert
Users.Add() 함수 인자로 User객체를 담는 형태로 DB에 Insert해줍니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
값을 Insert한 후에는 SaveChanges()를 실행시켜줘야 DB에 저장된다는거 잊지 마시기 바랍니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert SaveChanges()](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
하지만, 에러가 발생합니다. 왜 일까요?
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
Id를 넣어주지 않았기 때문에 발생한 에러입니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
우리가 만든 User클래스에 Id 프러퍼티가 설정되어 있으니까 당연히 채워줘야 겠지요.
수정 후 잘 추가 되었는지 확인해보겠습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert DB확인](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
추가한 값이 잘 들어가 있는걸 확인 할 수 있습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
그런데 id값을 일일이 추가해주는건 사실 번거로운 일이죠.
db상에 자동으로 id가 채워지게 할 수 없을까요?
먼저 테이블 마우스 오른쪽 클릭 후 디자이너 보기를 클릭합니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert](https://blog.kakaocdn.net/dna/cGY0YR/btrHNL84RX3/AAAAAAAAAAAAAAAAAAAAAN3We36avJGDQr-DtFHmCBfowMyT1zS03aQiI0MfJL5j/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=1nnEXp6YepMuBgHhCkoiOIArPGw%3D)
IDENTITY(1,1)를 ID에 추가해줍니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert](https://blog.kakaocdn.net/dna/bhh7W0/btrHN2JAH40/AAAAAAAAAAAAAAAAAAAAAJocsBkqsorLQIG3i6ukr4Qtm-9RZiEhLvz7qVyq4jMu/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=HheqX%2FD7OugIM%2F0lWPACU%2F0xog8%3D)
MSserver 에서는 AutoIncrement 기능을 IDENTITY(1,1)로 표현합니다.
첫번째 값이 1부터 시작한다는 의미이고, 두번째 값이 1씩 늘리겠다라는 의미입니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert 업데이트](https://blog.kakaocdn.net/dna/bMFo8W/btrHQqvmOg6/AAAAAAAAAAAAAAAAAAAAAB2oTh4eNQtzkLfySV2PTs5Hd4V7LuhkXEjJ1saaIBR5/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=yGq5NTZKOQq3I%2Br2mFonURDmXDg%3D)
이제 자동으로 ID가 채워지도록 설정을 해놓았기 때문에, 굳이 ID를 작성하지 않아도 객체 추가가 가능합니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 1) Insert 객체추가](https://blog.kakaocdn.net/dna/bg1DY2/btrHOTd0ytS/AAAAAAAAAAAAAAAAAAAAAP_QHXMbxWNrIb2uRJl4aBN-O3RUcAVK0twISQhSjwhY/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=mV2DupKK9T2OIaMRxEJLuEdixqM%3D)
2) Update
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 2) Update 업데이트 예제](https://blog.kakaocdn.net/dna/bJRgxj/btrHNEvao9r/AAAAAAAAAAAAAAAAAAAAAMVkGzi4p4AEQkOOklCGzxScti_jx21iBmpCuPDMuM1Z/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=fqr74ropZJlwbipF1Q5Jww8aU2U%3D)
ali의 나이를 28로 Update하고 싶습니다.
먼저 Where절을 통해 이름이 ali인 부분을 찾습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 2) Update Where 조건절](https://blog.kakaocdn.net/dna/CB4iZ/btrHQqhQmjh/AAAAAAAAAAAAAAAAAAAAAD2g369euEUfD6IPtRE-MO9rVDtL0i6HQ9CC1VKGFZuA/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=rVEVYaMSBNgc50Yu6KXBj1QifEc%3D)
하나의 값을 추출하기 위해 FirstOrDefault()를 사용했습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 2) Update firstordefault사용](https://blog.kakaocdn.net/dna/mOxZ4/btrHObF1pBu/AAAAAAAAAAAAAAAAAAAAAEor40eaQwmhDeMxBrT414H6HPl4dk3hKlzbARmUuvl-/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=aELxh%2F2UvRww3zCEeoX%2F34p1S5s%3D)
(FirstOrDefault가 낯선분은 해당 포스팅 참조)
수정하고 싶은 프러퍼티가 Age임으로 .Age에 접근하여 값을 변경해주고, SaveChanges()를 적용해줍니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 2) Update Age변경](https://blog.kakaocdn.net/dna/bkb9Ob/btrHOlhKktd/AAAAAAAAAAAAAAAAAAAAAGDjulpl4Dp0OpeAO41y9FcuLFZCyiMIiKHF69eQbTVn/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=nSV556LOAGRBRzAibtc%2FqK1fxB4%3D)
그 후 새로고침을 통해 DB를 확인하면 값이 정상적으로 변경된것을 알 수 있습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 2) Update output](https://blog.kakaocdn.net/dna/bJVmoh/btrHPOiJNh6/AAAAAAAAAAAAAAAAAAAAAH9jBzKuDkFWcbetv3RKIRdY5NrzCsdzeXvqFiHAYemc/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=aivEaT4J90HQ%2F2eNzvNjz7JRTQI%3D)
3) delete
(1) 1개 데이터 삭제
delete도 update와 같은 원리 입니다.
먼저 조건에 부합하는 값을 찾습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete Where조건문](https://blog.kakaocdn.net/dna/LXkao/btrHOt0F0Tc/AAAAAAAAAAAAAAAAAAAAAECBczYU2osyEdsjU3EYp66Mul3NrBEsZTOEAcsWCJSH/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=2z3Xs7IvZuov2OKLWGAclcGZjzk%3D)
찾은 객체를 Remove메소드의 인자로 넣습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete Remove](https://blog.kakaocdn.net/dna/VSN0D/btrHOTSE8qp/AAAAAAAAAAAAAAAAAAAAAMBTd04QkeYs9JQauAAM5KoqeD0rjmhRyEXvNAPsgaoi/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=SJQExjHEbqOYlTkm%2FYfGw0v1VRk%3D)
SaveChanges()를 통해 DB에 적용시켜줍니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete savechanges()](https://blog.kakaocdn.net/dna/2UvsG/btrHPeI0AXM/AAAAAAAAAAAAAAAAAAAAAMiWqkqYSB0MsDop2PS_5ZoQvWy9qcKeAHu5oyslkIax/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=ex94NkM%2B1Z50tm76%2Fua%2FpLC02ls%3D)
DB새로고침을 통해 확인해보니 정상적으로 삭제된것을 알 수 있습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete](https://blog.kakaocdn.net/dna/bBEVzp/btrHQpiXhe1/AAAAAAAAAAAAAAAAAAAAAE4VA-ncdz10421Nvlz2gqb41g2MD27pSwPnbBR2MXdl/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=FHnCjNdgdNu1jNj4APOJFR6gHzQ%3D)
그럼 더 나아가서 1개의 데이터가 아닌 여러개의 데이터를 동시에 삭제하고 싶으면 어떻게 할까요?
(2) 복수 데이터 삭제
나이가 30인 경우의 값만 뽑아서 삭제하고 싶습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete](https://blog.kakaocdn.net/dna/bc5Hfe/btrHPJWfM0v/AAAAAAAAAAAAAAAAAAAAAEANlg3kGEMiXKIFd0gWiIw0_6O-yaBRxJUW-SA3xB_E/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=R3V%2BrXlVyC9g3urcNlRX2XYCblU%3D)
해당 조건에는 2개 데이터가 해당되는데요.
앞서 했던 방법대로 해당 객체를 Remove() 안에 넣으려고하면 에러가 발생합니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete remove 에러](https://blog.kakaocdn.net/dna/bCW3aA/btrHNLBeKQ8/AAAAAAAAAAAAAAAAAAAAACfR8byu6HvDmHZ2zIEzI1Q0KzycQvIelacksqtFi5zU/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=8TZRTwK6FkVqv9sbfUzL7NPGJvI%3D)
대신 RemoveRange()로 대체 해주면 정상 작동합니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete RemoveRange변경](https://blog.kakaocdn.net/dna/lnFyv/btrHOATi2Bp/AAAAAAAAAAAAAAAAAAAAAIuLaOyHtcjI_NT9jgnGl03C2gBXyhXTUh4gnockJK_l/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=OtKXPdhrXsPSKdKgQWX1Lu18em0%3D)
새로고침을 통해 DB를 확인해보니 정상적으로 삭제된것을 알 수 있습니다.
![[c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete [c#] Insert, Update, Delete 하는법 with EntityFramework - undefined - 3) delete](https://blog.kakaocdn.net/dna/bzArvx/btrHRNKDa6L/AAAAAAAAAAAAAAAAAAAAAMyRL2_aB4_xzKXSCEiQpvnW3Z5UazePqI1vEUwS2fNY/img.png?credential=yqXZFxpELC7KVnFOS48ylbz2pIh7yKj8&expires=1753973999&allow_ip=&allow_referer=&signature=uMm%2FECarWfyHaLZ1kZtYQN2imlk%3D)
'c#' 카테고리의 다른 글
[c#] Entity Framework 사용 방법(code-first) (0) | 2022.08.19 |
---|---|
[c#] 의존성 주입(dependency Injection) 이란? (2) | 2022.08.10 |
[c#] localdb에 EntityFramework 연결 하는 방법 (0) | 2022.07.19 |
[c#] LINQ First vs Single | FirstOrDefault vs SingleOrDefault 차이 (0) | 2022.07.15 |
[c#] SQL in / not in 기능을 LINQ로 구현 (0) | 2022.07.15 |
댓글