Entity Framework 컨텍스트를 Using 문에 넣어야합니까?
Entity Framework 컨텍스트 개체는 "개체 컨텍스트에서 사용하는 리소스를 해제"하는 Dispose () 메서드를 구현합니다. 정말로 무엇을합니까? 항상 using {} 문에 넣는 것이 나쁜 것일 수 있습니까? using 문을 사용하거나 사용하지 않고 사용하는 것을 보았습니다.
특히 WCF 서비스 메서드 내에서 EF 컨텍스트를 사용하고, 컨텍스트를 만들고, linq를 수행하고, 답변을 반환 할 것입니다.
편집 : 이것에 대해 궁금해하는 유일한 사람이 아닌 것 같습니다. 또 다른 질문은 Dispose () 메서드 내부에서 실제로 일어나는 일입니다. 어떤 사람들은 그것이 연결을 끊는다고 말하고 어떤 기사는 그렇지 않다고 말합니다. 거래는 무엇입니까?
컨텍스트를 작성하는 경우 나중에 폐기해야합니다. using
문장 을 사용해야한다면 문맥의 수명에 따라 달라집니다.
메서드에서 컨텍스트를 만들고이 메서드 내에서만 사용하는
using
경우 추가 코드없이 예외 처리를 제공하므로 실제로 문을 사용해야합니다 .컨텍스트를 더 오랫동안 사용하는 경우 (즉, 수명이 메서드의 실행 시간에 구속되지 않음)
using
문을 사용할 수 없으며Dispose()
자신 을 호출 하고 항상 호출하도록주의해야합니다.
Dispose()
객체 컨텍스트에 대해 무엇을 합니까?
나는 코드를 보지 않았지만 적어도 기본 소켓이나 전송 메커니즘이 사용하는 리소스와의 데이터베이스 연결을 닫을 것으로 예상합니다.
당 Progamming 엔티티 프레임 워크 : "당신은 명시 적으로 ObjectContext를 처분하거나 작업을 할 수있는 가비지 컬렉터를 위해 기다릴 수 있습니다."
간단히 말해서 using 문이 필요하지는 않지만 가비지 수집을 기다리는 대신 리소스가 즉시 해제되므로 ObjectContext 사용을 완료했음을 알고있는 것이 가장 좋습니다.
가비지 수집기가 항목을 처리하는 시기를 모르기 때문에 IDisposable을 구현하는 개체를 사용 블록으로 처리 한 경우를 알면 항상 래핑하는 것이 좋습니다 .
EF5 및 이전 버전
using { ...
// connecction open here.
...
context.Blogs.Add(blog);
context.SaveChanges(); // query etc now opens and immediately closes
...
context.Blogs.Add(blog);
context.SaveChanges(); // query etc now opens and immediately closes
}
EF6 및 이후 버전
using {
// connecction open here.
...
context.Blogs.Add(blog);
context.SaveChanges();
// The underlying store connection remains open for the next operation
...
context.Blogs.Add(blog);
context.SaveChanges();
// The underlying store connection is still open
} // The context is disposed – so now the underlying store connection is closed
참조 : http://msdn.microsoft.com/en-us/data/dn456849#open5
항상 IDisposable을 구현하는 클래스를 인스턴스화하는 경우 해당 클래스에 대해 Dispose를 호출해야합니다. 하나를 제외한 모든 경우에 이것은 사용 블록을 의미합니다 .
삭제하면 ObjectContext는 소유 한 다른 개체를 삭제합니다.
실제 데이터베이스 연결, 즉 일반적으로 SqlConnection을 래핑하는 EntityConnection과 같은 것들을 포함합니다.
따라서 SqlConnection이 열려 있으면 ObjectContext를 삭제할 때 닫힙니다.
나는 ADO.net과 EF v.6 모두에 대해이 것을 실제로 테스트하고 SQL 테이블의 연결을 관찰했습니다.
select * from sys.dm_exec_connections
테스트 할 방법은 다음과 같습니다.
1) ADO.net 사용
using(var Connection = new SqlConnection(conString))
{
using (var command = new SqlCommand(queryString, Connection))
{
Connection.Open();
command.ExecuteNonQueryReader();
throw new Exception() // Connections were closed after unit-test had been
//finished. Expected behaviour
}
}
2) ADO.net 사용
var Connection = new SqlConnection(conString);
using (var command = new SqlCommand(queryString, Connection))
{
Connection.Open();
command.ExecuteNonQueryReader();
throw new Exception() // Connections were NOT closed after unit-test had been finished
finished. I closed them manually via SQL. Expected behaviour
}
1) 사용시 EF.
using (var ctx = new TestDBContext())
{
ctx.Items.Add(item);
ctx.SaveChanges();
throw new Exception() // Connections were closed, as expected.
}
2) 사용하지 않는 EF
var ctx = new TestDBContext();
ctx.Items.Add(item);
ctx.SaveChanges();
throw new Exception() // Connections WERE successfully closed, as NOT expected.
I don't know why is it so, but EF automatically closed connections. Also All the patterns of repository and UnitOfWork which use EF don't use using. It's very strange for me, because DBContext is Disposable type, but it's a fact.
Maybe in Microsoft they did something new for handling?
I have noticed (although in only one application) that the explicit disposal was causing thread abort exceptions in mscorlib which are caught before the application code, but at least in my case resulting in a noticeable performance hit. Haven't done any significant research on the issue, but probably something worth consideration if you are doing this. Just watch your DEBUG output to see if you are getting the same result.
If Dispose closes connection to DB it is a bad idea to call it. For example in ADO.NET connections are in connection pool and never be closed before timeout or application pool stop.
'programing tip' 카테고리의 다른 글
C / C ++ 프로그램이 main () 전에 충돌 할 수있는 방법이 있습니까? (0) | 2020.11.23 |
---|---|
jstl foreach는 마지막 레코드의 요소를 생략합니다. (0) | 2020.11.23 |
클립 보드에 데이터를 안전하게 복사하기위한 플래시 기반 ZeroClipboard의 HTML5 대안? (0) | 2020.11.22 |
Entity Framework에서 외래 키 관계를 추가하는 방법은 무엇입니까? (0) | 2020.11.22 |
Python으로 sys.path를 설정하는 것은 무엇이며 언제입니까? (0) | 2020.11.22 |