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

c# - Why re-initiate the DbContext when using the Entity Framework?

I don't know if there is a better way to use the DbContext because it is not recommended to set is as static when working with WCF. So we are creating it each time we want to access the database.

Knowing all the advantages of using Entity Framework, some become useless since we are recreating the DbContext each time; and more may cause overhead since the process of creating big entity models is to be considered.

What is your opinion?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Managing Lifetime

You're correct that a single static instance of DbContext is usually not recommended:

The more you use an ObjectContext, generally the bigger it gets. This is because it holds a reference to all the Entities it has ever known about, essentially whatever you have queried, added or attached. So you should reconsider sharing the same ObjectContext indefinitely.

These comments apply directly to the DbContext, because it wraps wraps ObjectContext to expose "simplified and more intuitive APIs." [see documentation]


Cost of Construction

The overhead of creating the context is relatively low:

The reality is this cost is actually pretty low, because mostly it simply involves copying, by reference, metadata from a global cache into the new ObjectContext. Generally I don’t think this cost is worth worrying about ...

The common way to work with a short-lived context is to wrap it in a using block:

using(DbContext context = new SomeDbContext())
{
    // Do work with context
}

To ease with testing, you may want to have your DbContext implement some IDbContext interface, and create a factory class ContextFactory<T> where T : IDbContext to instantiate contexts.

This allows you to easily swap any IDbContext into your code (ie. an in-memory context for object mocking.)


Resources


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

...