Thursday, January 15, 2015

Storage: Entity Framework - Leveraging EF in a multi-tiered enterprise application

EF is not a data access layer but rather a tool that helps build a data access layer with less code. The following diagram depicts how EF can be utilized in a multi-tiered enterprise application. Each box can be thought of a separate layer/tier (or at a minimum, a separate Visual Studio project).


  • Repository creates and uses EF DbContext. It may create a new DbContext for each request (disconnected client) or create, keep and use a singleton instance (connected client) of a DbContext . DbContext tracks changes. If changes are made to POCOs that are not monitored by DbContext (via DBSet), EF must be apprised of these changes via the EF API. If the domain is large, multiple domain-specific Repositories may be implemented.
  • Repository abstracts the Storage API. Behind the scenes, it can use a persistence scheme other than EF, if it decides to do so later. DTOs (Data Transfer Objects) are persistence-technology independent data structures (POCOs) that shuttle the data between the Domain Model and the Repository.
  • Domain Model uses the Storage API exposed by the Repository. The Repository can be "mocked" to facilitate unit testing of the Domain Model without having to create a real SQL Server database.
  • Domain Model has its own set of POCOs that form the Data Contracts for the application. These are not the same as DTOs (we should be able to change the DTOs without breaking the Application API). The Domain Model exposes its functionality through a well-defined API and Data Contracts.
  • Clients (Background daemon, WPF, ASP.NET,...) use the Domain Model and are decoupled from the SQL Server Database, EF, Repository, and DTOs. The clients are only dependent on the Data Contracts and Application API exposed by the Domain Model.