Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

c# - Should Entity Framework Context be Put into Using Statement?

The Entity Framework context object implements a Dispose() method which "Releases the resources used by the object context". What does it do really? Could it be a bad thing to always put it into a using {} statement? I've seen it being used both with and without the using statement.

I'm specifically going to use the EF context from within a WCF service method, create the context, do some linq and return the answer.

EDIT: Seems that I'm not the only one wondering about this. Another question is what's really happening inside the Dispose() method. Some say it closes connections, and some articles says not. What's the deal?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you create a context, you must dispose it later. If you should use the using statement depends on the life time of the context.

  1. If you create the context in a method and use it only within this method, you should really use the using statement because it gives you the exception handling without any additional code.

  2. If you use the context for a longer period - that is the life time is not bound by the execution time of a method - you cannot use the using statement and you have to call Dispose() yourself and take care that you always call it.

What does Dispose()do for an object context?

I did not look at the code, but at least I exspect it to close the database connection with its underlying sockets or whatever resources the transport mechanism used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...