Is it always better to use 'DbContext' instead of 'ObjectContext'?

bevacqua picture bevacqua · May 7, 2012 · Viewed 7.3k times · Source

I just downloaded EntityFramework.dll v4.3. I've found a number of questions that compare DbContext vs. ObjectContext. But most of these are from 2010, or early 2011.

I'd like to read more on the subject. Specifically, are there any books on DbContext I can get my hands on? I also want to know, as of today, what are the limitations of DbContext when comparing it to its older brother the ObjectContext?

I realize that DbContext is more compact in that it exposes fewer properties. This suggests to me that I should migrate from ObjectContext. But, if I do this migration, will I give up any capabilities? For example, I've read that DbContext doesn't have the STE (Self-tracking entities) capability. Does this still hold true and is it a concern?

Answer

Ladislav Mrnka picture Ladislav Mrnka · May 7, 2012

I'd like to read more on the subject. Specifically, are there any books on DbContext I can get my hands on?

Your question does not start off well because a single Google query will give you an answer for this. There is an excellent book about DbContext itself — it doesn't contain anything about the Code First approach, but I guess that is really not the point of your question.

I've found a number of questions that compare DbContext vs. ObjectContext. But most of these are from 2010, or early 2011.

If you just want to replace ObjectContext + EDMX with DbContext + EDMX, the comparison is still the same. DbContext is a wrapper around ObjectContext and its feature set didn't grow up except with respect to those features related to Code First and Migrations.

I realize that DbContext is more compact in that it exposes fewer properties. This suggests to me that I should migrate from ObjectContext.

Yes, it is more compact and it simplifies most common tasks that you have to do with the context. For more complex tasks, you can still convert a DbContext instance to an ObjectContext instance through IObjectContextAdapter.

But, if I do this migration, will I give up any capabilities? For example, I've read that DbContext doesn't have the STE (Self-tracking entities) capability. Does this still hold true and is it a concern?

STE was created for ObjectContext and I don't think it was ported to DbContext, but you can try to implement this capability yourself.

STEs are just a template with an idea to solve some problem. It appeared as a good theoretical solution but it wasn't very well accepted by the developer community because the solution is not very good for real world scenarios. It is also the reason why other more important features are being developed instead of improving or porting the template.