잊지 않겠습니다.

Pro LINQ (02)

Book 2009. 1. 7. 18:50
LINQ에서 사용되는 select, where, selectmany는 지연된 동작(deferred operation)을 행한다.

LINQ query가 실행하는 동시에 각 객체를 얻어내고 실행하는 것이 아닌, 결과가 이용될 때에 각각의 객체를 얻어오는 형식이 된다. 

다음과 같은 예제 LINQ query를 보면..
    public class DataContextLinq
    {
        public void QueryDatas()
        {
            NorthwindDataContext dbContext = new NorthwindDataContext(@"Data Source=Y2K\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True");
            dbContext.Log = Console.Out;

            Console.WriteLine("Queried datas - Start");
            var products = from p in dbContext.Products where p.Color == "Red" select p;
            Console.WriteLine("Queried datas - End");

            Console.WriteLine("Deferred Operation - Start");
            foreach(Product product in products)
            {
                Console.WriteLine(product.Name);
            }
        }
    }

여기에서 var products = from p in dbContext.Products where p.Color == "Red" select p; 에서 검색이 이루어지는 것이 아닌, 각 객체를 얻어낼 때에 그 Query를 던지게 된다. 결과는 다음과 같다. 



이는 foreach 문에서 기존의 DataReader에서 MoveNext() 구문을 호출하게 되는 것과 동일하게 움직이게 된다. 
또한 값을 처음호출할때, DB에 대한 Connection을 연결하기 때문에, DBContext 객체의 경우에는 생성 및 삭제에서 조금 덜 엄격한 IDispose role을 따르게 된다. 
Posted by Y2K
,