C# – the correct reusable architecture using Entity Framework for common database tables and services

ccode-reusedatabaseenterprise-architectureentity-framework

Context

I have a line of business application "MyApp" in C# using EF. Layers are separated as

  • MyResusableLib.DataAccess // Class Lib: EF based utils, extension methods,
  • MyApp.DataAccess // Class Lib: EF edmx, generated Model classes
  • MyApp.DataServices // Class Lib: Depends on Model classes in MyApp.DataAccess (Note: Services are just POCOs and has nothing to do with a web API. For example PaymentService.Storno(…))
  • etc

I discovered, that some universal tables (at least five) will be common in all my future line of business applications. So implemented high level services should not be copied over MyApp1.DataServices to MyApp2.DataServices, instead should be placed a newly created MyReusableLib.DataServices class lib

Problem:

The EF context and model classes will be in future created MyAppX.DataAccess. However MyReusableLib.DataServices depends on those model classes.

Question:

What is the best architecture to overcome the problem, and enjoy a MyReusableLib.DataServices with its high level services over the persistent storage?

Proposed Solution:

Only one solution comes in my mind, but I am not sure. Especially I do not know if there are drawbacks, and also do not know if there is a better practice. One for sure: I would like to end with a DRY solution.

  • I will have two EF edmxs and contexts (pointing to the very same database when connection strings will be configured in my future MyAppX.)
  • The first EF edmx context will be defined in MyReusableLib.DataServices and will contain the five reusable tables/entites.The implemented services (also in the assembly) can use those model classes.
  • The second EF edmx context will be defined in my future MyAppX. Will contain all specific tables and will not contain the reusable tables.
  • The physical database for MyAppX will contain both the reusable tables and the specific tables.

Best Answer

  • MyModels - class lib. No dependencies

  • IMyDataRepository - interface. Depends on MyModels

  • MyDataRepository_EfSql - depends on MyModels and IMyDataRepository
    and Entity framework

    • private EF Context private EF Models

    • private EF Model to Domain Model mapping

  • MyApplication - depends on all three. But the repository is loosely
    coupled via dependency injection