Lessons Learned from Entity Framework

So I'm starting a new project, and we've made the decision to use the ADO.NET Entity Framework for talking to the database.

I actually found it quite difficult to get started. Examples on the web seemed to assume that I already had everything installed and ready to go. Step one was invariably "Add a new ADO.NET Entity Data Model". That wasn't available in my "Add New Item" dialog, so I set out to discover how to add the bits I was clearly missing.

After hunting for a while for a download, I found a CTP Preview 1 built on .Net 4.0 (I'm running 3.5), and some Entity Framework tools released as a CTP in 2007.

Lesson 1: Everything you need comes with the Microsoft .NET Framework 3.5 Service Pack 1.

Of course, when I try to find the misleading links now, I find the real one straight away. Hopefully your google-fu won't fail you as mine obviously did.

I had a quick play with it and found that creating classes and relationships between them was mindblowingly easy. Build up your pretty diagrams or get the designer to build them from a database and suddenly your code can create objects, run LINQ queries against them, bind them to UI controls and keep track of changes as you go. Brilliant!

So I got to work building up a sample object tree for our new application. When I was done, I looked for the option to persist the changes to the database.

Lesson 2: You can update your models based on database changes, but not the other way around (it's coming in 4.0 though).

Damn, database first. Back to the start.

No problem, I abandoned my design and started with the database. Once the tables were built, generating EF data models was a piece of cake.

Next step - dependency injection for testing. I don't want to be bound to the database, particularly for testing. I want to be able to inject fake objects for my tests.

Lesson 3: EF creates concrete model classes and database contexts. Dependency Injection is not easy.

Honestly, we were prepared for this one based on some presentations we saw at Tech.Ed. We have come up with a solution for this, too. It looks good on paper and everything seems to compile and run ok, but we're yet to see whether this holds true as we dig deeper.

Basically, we're leaving the concrete models as they are, but we're extracting an interface for the ObjectContext class that's generated. Our proxy will provide a fake ObjectContext which doesn't talk to the database, but it will mock out real model instances. If you have any better ideas for this problem though, let me know.

Damian Brady

I'm an Australian developer, speaker, and author specialising in DevOps, MLOps, developer process, and software architecture. I love Azure DevOps, GitHub Actions, and reducing process waste.

--