2011-02-24 4 views
0

왜 여기가 잘못 되었습니까?세션이 닫혀 있습니다 - 성 ActiveRecord

public IQueryable<Customer> GetAllCustomers() 
{ 
    using (SessionScope scope = new SessionScope()) 
    { 
     return scope.AsQueryable<Customer>(); 
    } 
} 


var result = from x in GetAllCustomers() select x; 
Assert.Greater(result.Count(), 0); 

System.ObjectDisposedException : 세션이 종료됩니다! 개체 이름 : 'ISession'

이 게시물이 내게 ​​도움이되지 않았다 : Castle ActiveRecord error "Session is closed"

답변

3

것은 실제 쿼리가이 라인에서 실행되지 않는 것입니다 :

scope.AsQueryable<Customer>(); 

만 나중에 조회 할 수있는 IQueryable 개체를 반환하기 때문에. 분명히, 세션이 이미 (당신이 using 블록을 종료 할 때이 종료됩니다) 폐쇄,이 시점에서

Assert.Greater(result.Count(), 0); 

: 당신이 데이터에 액세스 할 때

그래서,이 실행됩니다. 가능한 솔루션

하나는 GetAllCustomers 방법 밖으로 SessionScope를 이동하는 것입니다 :

public IQueryable<Customer> GetAllCustomers(SessionScope scope) 
{ 
    return scope.AsQueryable<Customer>(); 
} 


using (SessionScope scope = new SessionScope()) 
{ 
    var result = from x in GetAllCustomers(scope) select x; 
    Assert.Greater(result.Count(), 0); 
} 
+0

감사 파블로. 쿼리가 더 이상 사용되지 않을 때를 감지 할 수 있는지 알고 있습니까? – Eduardo

3

당신이 result.Count() (LINQ 쿼리가 느리게 실행) 실행하면 쿼리가 실제로 실행되지만, SessionScope가 이미 그때까지 배치되었습니다.

웹 프로젝트 인 경우 HTTP-request-scoped SessionScope을 사용하십시오.

관련 문제