이번 포스트에서는 datagridview control 에 데이타를 select, insert, update, delete 시키는 모든 연산을 sql db 의 northwind db를 이용해서 작업해 보도록 하겠습니다.
일단은 sql 2012 의 norhwind db를 다음의 사이트에서 다운로드를 받아서 설치를 합니다.
http://businessimpactinc.com/install-northwind-database/
최종적인 결과 화면입니다.
프로젝트 선택 => [추가] => [새항목] => [데이타] =>[LINQ to SQL 클래스] 선택하고 이름을 "northwind" 라 입력을 합니다.
그리고, 테이블을 모두 drag & drop 으로 끌어다 좌측 윈도우에 위치 시키며, 스토어 프로시저를 끌어다 오른쪽 창에 위치 시킵니다.
이제, northwind.dbml 파일 하단에 있는 northwind.designer.cs 파일을 열고 확인 해 보면,
맨 상단에 northwindDataContext 클래스가 있으며 하단으로 테이블명으로 되어 있는 클래스들을 확인 할 수 있습니다.
이번 예제에서는 Customers 테이블에 연산하는 것을 예시로 보입니다.
[Get Data] 버튼을 클릭했을 시 보이는 method, 모든 데이타를 가져옵니다.
1 2 3 | northwindDataContext dbContext = new northwindDataContext(); dataGridView1.DataSource = dbContext.Customers; |
[Insert] 버튼 클릭시 작동하는 method 입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | using (northwindDataContext dbContext = new northwindDataContext()) { var userInfo = dbContext.Customers.Where(u => u.CustomerID == textCustomerID.Text); if (userInfo.Count() > 0) { MessageBox.Show( "[CustomerID] 가 중복입니다. 다른 것으로 변경하시기 바랍니다." , "에러" , MessageBoxButtons.OK, MessageBoxIcon.Error); } else { Customers customer = new Customers { CustomerID = textCustomerID.Text, CompanyName = textCompanyName.Text, ContactName = textContactName.Text, ContactTitle = textContactTitle.Text, Address = textAddress.Text, City = textCity.Text, Region = textRegion.Text, PostalCode = textPostalCode.Text, Country = textCountry.Text, Phone = textPhone.Text, Fax = textFax.Text }; dbContext.Customers.InsertOnSubmit(customer); dbContext.SubmitChanges(); GetData(); } } |
[Update] 버튼 클릭시 작동하는 method 입니다.
1 2 3 4 5 6 7 8 | using (northwindDataContext dbContext = new northwindDataContext()) { Customers customer = dbContext.Customers.SingleOrDefault(x => x.CustomerID == textCustomerID.Text); customer.CompanyName = textCompanyName.Text; dbContext.SubmitChanges(); } GetData(); |
[Delete] 버튼 클릭시 작동하는 method 입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | using (northwindDataContext dbContext = new northwindDataContext()) { try { Customers customer = dbContext.Customers.SingleOrDefault(x => x.CustomerID == textCustomerID.Text); dbContext.Customers.DeleteOnSubmit(customer); dbContext.SubmitChanges(); } catch (ArgumentNullException ex) { MessageBox.Show(ex.Message, "에러" , MessageBoxButtons.OK, MessageBoxIcon.Error); } } GetData(); |
전체 소스
'C# with LINQ to SQL' 카테고리의 다른 글
LINQ - 스토어드 프로시저 호출 (select) (0) | 2015.07.06 |
---|---|
LINQ - SQL 쿼리문 보기 (0) | 2015.07.02 |
LINQ - 로그인창 적용 (0) | 2015.06.25 |
LINQ - 조인(내부조인, 그룹조인, 왼쪽 우선 외부 조인) (0) | 2015.06.22 |
LINQ - 그룹핑2 (0) | 2015.06.19 |