블로그 이미지
따시쿵

calendar

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 31

Notice

2015. 7. 2. 17:55 C# with LINQ to SQL

이번 포스트에서는 LINQ to SQL 에서 생성 된 sql 문을 확인 해 보도록 하겠습니다.

 

windows form 타입을 기준으로 알아 보도록 하겠습니다.

1. dbContext.Log = Console.Out;

 

가장 간단하게는 다음과 같이 작업해 주시면 됩니다.

            northwindDataContext dbContext = new northwindDataContext();
            dbContext.Log = Console.Out;    // 출력창에 sql 문을 출력하는 명령문
            dataGridView1.DataSource = dbContext.Customers;

 

 

[Get Data] 버튼을 클릭시 출력창에 나오는 sql 문입니다.

 

만약 웹 페이지에서 작업을 한다면 위 구문을 다음으로 변경합니다.

dbContext.Log = Response.Out;

 

 

2. 문자열을 Trace.WriteLine 을 이용해서 출력창에 쿼리문을 보이는 방법

 

1번 쿼리와 데이타 쿼리 결과가 같으며 출력창에 보이는 쿼리도 같습니다.

            northwindDataContext dbContext = new northwindDataContext();

            var linqQuery = from customer in dbContext.Customers
                            select customer;
            string strQuery = linqQuery.ToString();

            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));  
            Trace.AutoFlush = true;
            Trace.WriteLine(strQuery);        // 출력창에 sql 문을 출력하는 명령문          

            dataGridView1.DataSource = linqQuery;

 

 

3. DataContext.GetCommand.CommandText 를 이용하는 방법

            northwindDataContext dbContext = new northwindDataContext();

            var linqQuery = from customer in dbContext.Customers
                            select customer;

            string strQuery = dbContext.GetCommand(linqQuery).CommandText;

            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); 
            Trace.AutoFlush = true;
            Trace.WriteLine(strQuery);      // 출력창에 sql 문을 출력하는 명령문

            dataGridView1.DataSource = linqQuery;

 

 

 

4. SQL Profiler를 이용하는 방법

 

위에서 설명한 방법들이 프로그램 파트에서 이루어진 부분이라면 지금은 디비 파트에서 실행되는 명령어를 프로파일러를 이용해서 캡쳐한 것입니다.

 

어떤 방법을 이용하든 생성된 sql 문은 동일합니다.

 

전체 소스

MyLINQ9.zip

 

posted by 따시쿵