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
134 views
in Technique[技术] by (71.8m points)

c# - Should data contexts be static?

I am using entity framework 4 and I create an datacontext for model in one of the base classes. But I was in profiling it and the context is being created every time I try to query, So I thought of making it static so that it is created only once and reused always.

Do you think this is the best way to do it and data/object context should always be made static? Are there any disadvantages to making it static? Should data contexts be static or non-static? Any ideas or suggestions are welcome.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

No. They should not always be static.

You can actually run in to many more issues with a Static Data Context rather than the non-static equivalent (like multiple users from separate sessions accessing the same context from multiple threads).

I'm not going to go into the detailed explanation since there are some very good blog posts out there covering the details:

Linq to SQL DataContext Lifetime Management - Rick Strahl's Web Log (may not seem relevant, but still is)

Making Entity Framework (v1) work, Part 1: DataContext Lifetime Management (for a possible alternative if you don't like Rick's solution)


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

...