Why Entity Framework isn’t a Good Model, Part II: DbContext

243
2 min readJan 12, 2018

--

This is the second part of my anti-EF screed. Continuing on the theme of object oriented principles, I want to challenge the idea of the database context and explain why I think it should be broken down. Though they are not sequential, be advised that if you would like, you may read the first installment here.

DbContext and the Single Responsibility Principle

Here’s an exercise for you: Tell me what the word “Context” means in Entity Framework. Give me a quick summary of every purpose that the Context serves and why you think the writers of Entity Framework chose the word “Context” to represent this object.

The Context has a number of data structure objects that represent tables. The Context manipulates and returns the database data using these data structures. This includes how to map C# models and members to database table and column names. That’s a pretty good start. Except it also handles the database connection information including connection strings and timeout information and what flavor of SQL to execute against the database. It also tracks the state changes for every object. And also a ton of general configuration data for how to do all that. And next week, I’ll probably learn a couple other things it does.

Reading that, it should be apparent why I think that the Context violates the single-responsibility principle. It does all the things. The harder part is defining why that’s important. After all, what do I as a user of the library really care if the library is difficult to maintain? That’s a job for the maintainers.

But (with the utmost respect to Uncle Martin) I think there’s another reason to limit the number of responsibilities in an abstraction, and that is that an abstraction should mean something. The word “Context” doesn’t mean anything in this… context (dammit). It can’t be named; it has to be explained, and at great length. Don’t get me wrong — I’m pro-explanation and pro-comment. There are certainly times when code can’t be self-documenting because domain language just doesn’t have the right words to explain in just a few characters, even if it is very simple on a mathematical level. In this case, though, the Context can’t be given a name because it just does too much. It’s just a massive, stateful God-object that encapsulates every possible piece of information contained in or relating to the database. It can’t be named because it’s a bad abstraction.

As blog articles go, maybe this one’s a little short, but as rants go, I think this one is plenty long enough for anybody. In short order, I’ll be publishing a couple more thoughts on the subject of Entity Framework. Thanks for reading!

You can read the first installment of this series right here.

--

--

243

Civic tech fanatic. Senior ASP.NET MVC / C# developer. Web Bureaucrat. Opinions are mine, but the bugs are all from the previous maintainer.