Image Image Image Image Image
Scroll to Top

To Top

Clean Code Developer Here I share my ideas about software craftsmanship.

ADO.NET Unit Testable Repository Generator

At work we are going to do a big refactoring on a ASP.NET MVC project. I learned a lot of this project. One hard lesson was: the code base is as good is the guidance of the senior coders. If you know the power of the Entity Framework, then you also know the countless possibilities to write wicked code. But I’m present at the office only for days a week. That’s why I’m planning to write some articles in the next time.

We now decided to radically limit EF’s possibilities to a handsome DAL (data access layer), which is testable, stateless, easy to use and brutally simple. Please keep in mind that those limitations are not a real handicap. In fact they should allow newcomers to focus on their real target.

These are some details about the project:

  • Usage of a Service- and Repository Layer
  • Data Objects are all POCOs (Plain Old CLR Object)
  • Entity Framework is the DAL underneath the repository (some people are arguing that EF is already fulfilling the Repository-Pattern)
  • Dependency Injection (DI) is done with the help of Unity
  • Unit Tests are running on the TFS (Team Foundation Server), therefore we mix MSTest and NUnit

At office and for my own projects I used the ADO.NET C# POCO Entity Generator for a while. Here is a great article describing this approach:
Walkthrough: Test-Driven Development with the Entity Framework 4.0
At this point I also recommend the book Programming Entity Framework, 2nd edition by Julia Lerman, which also covers Unit Testing in one chapter.

If you have a lot of small repositories, then you have lot of recurring stuff to do. This totally ignores the DRY-principle. (Don’t Repeat Yourself) For that reason Rab Hallett has extended the “ADO.NET C# POCO Entity Generator” with some more features. Please have a look at his articles:

This extension is a perfect starting point for some more handy code generation, called “ADO.NET Unit Testable Repository Generator”.

With this extension you will get a complete solution:

  • all functionalities of the ADO.NET C# POCO Entity Generator, which includes:
    • a compatible ObjectContext (replaces the “Entities-Class”)
    • all entity types as POCOs (Plain Old CLR Objects)
  • as well as:
    • an Interface for the ObjectContext
    • a mock of the ObjectContext (provides access to ObjectSets)
    • a mock that implements IObjectSet (stores data)
    • a partial Repository class
    • an abstract Unit Test class
    • optional: support for Microsoft Unity *
    • optional: equality members for the POCOs (Equals and GetHashCode) **

You can download the stable version here:
(84,0 KB) from the Visual Studio Gallery

The new Interface now hides all advanced functionalities of the EF.
This simplifies things dramatically. Welcome back to the good old Linq-To-SQL days!

» In my next post I will explain the usage with a short walkthrough.

Many thanks to the guys from Microsoft and to Rab Hallett who offered their work under the Microsoft Public License ! :-)

* Use the preprocessor definition “DO_NOT_USE_UNITY”, if you do not want to utilize the Unity-Framework.
** Some people might prefer the POCOs completely plain. For that case you should define the directive “DO_NOT_INCLUDE_ EQUALITY_MEMBERS”.

Please note: I renamed to extension from “ADO.NET Mocking Context Generator – Extended” to “ADO.NET Unit Testable Repository Generator”.

Tags | , , , , , ,


  1. Blogged:… – ADO.NET Mocking Context Generator – Extended #dotnet #ccd #fb

  2. dixit

    What is ES ?

  3. dixit

    yes sorry

  4.… – @ .NET Geeks: Should I implement Equality Members for better Unit Testing of POCOs? Or do you prefer them plain?!?

    • cessor

      @JohannesHoppe How about a post sharp aspect that can be attached?

      • @cessor Yeah! Taking a sledgehammer to crack a nut! ^_^ But then I could completely strip T4 code generation! ;-)

        • cessor

          @JohannesHoppe Klar, ich will nur sagen: Verkünstel dich nicht! Ich würde jedoch keine Equality Members by default haben wollen.

  5. Hi Johannes,

    I wanted to try this on a much meatier EDM so I just tried this on Julie Lerman’s BreakAway model from the sample code in her fantastic book.

    I started with the following downloads for the Programming Entity Framework – 2nd Edition Book:

    * BreakAway Database for 2nd Edition (exe installer) (revised 8/13/2010)
    * Customized Model Post Chapter 16 (or take the model from the solution for one of the later chapters such as Chapter 24).

    I’ve come across some hopefully small issues that may well be very easy for you to fix in a future version of your template – if you’d be so kind…

    Here’s the repro:

    I took the following steps…

    Created an empty Class Library project

    Used NuGet Package Manager to add a new Library Package Reference to Microsoft.Patterns.Unity

    Added library reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

    Copied the BreakAway.edmx and a suitable App.Config from one of Julie’s book solutions that I’d already configured to point to the database already imported into SQL Express.

    Here are the issues I’ve found so far:

    Issue 1

    For all classes that subclass another entity (e.g. Customer is a subclass of Contact) I get the following compiler warning:

    ‘Model.Customer.CombineHashCodes(params object[])’ hides inherited member ‘Model.Contact.CombineHashCodes(params object[])’. Use the new keyword if hiding was intended.

    It looks like it would be tidier to either:

    1) Introduce a common base class where the Equality operations can live – also has the benefit of complying with the DRY principle.

    2) Somehow check whether the base type is not null, in which case no need to add the method again, if it’s going to be identical.

    Julie Lerman does something similar to the above in her customisations of the Microsoft ADO.NET C# POCO Entity Generator template (see addition of a BaseTypeName method in Section 18.1.3 – Example 18-3).

    Issue 2

    using System;

    Needs to be added to the .Context template – i.e. to the code for the ObjectContext class to account for cases where the Type of arguments to one or more of the function imports is a Nullable.

    I assume it needs to be added to WriteHeaderConcreteContextBody() at line 723.

    If I manually fix the above issues my model will compile without errors or warnings. I’ve not tried running data through the model yet though :-)

    Do you host the source somewhere where you could accept patches?

    Cheers, Rohan.

    • So much energy shouldn’t be wasted! :-)
      I created a CodePlex page and invited you. Welcome to the party!

      I would be happy to see your patches!

      Regarding the issues:

      Issue 1.

      I would recommend that you add the BreakAway.edmx and (if required) the mdf Database file to the source control. A dedicated test project wouldn’t be a bad idea.
      With T4 templates you do not violate the DRY principle. The code generation produces the repeated code. So here I highly recommend to keep it KISS and to not add a new base class.

      Issue 2:

      using System; — Oops!! Too much cleanups from the original code.

  6. Matthias

    I am quite a rookie in Ado.Net and the EF but nevertheless I am very interested in TDD.
    At first glance your repository generator makes a very good impression for my needs. But I am wondering if the repository is suitable for entity sql transaction.
    (I hope this is not a dump question easy derivable from your blog)

  7. I think all the test pass… this may be shipable! Using the Unit Testable Repository Generator

Kommentar absenden