entity-frameworkdependency-injectionentity-framework-migrationsirepository

About Dependency Injection, IRepository and EF Migrations scenarios


I am confused about how EF Migrations handle scenarios where my repositories are generic( IRepository<>) and are injected in runtime by my selected Dependency Injector Tool. You know that the Database is updated/sync by Migrations using three elements:

  1. Database Model (Object context and DbSet<> properties)
  2. Migrations clases inside the Migration folder
  3. The already existing Database(if any)

You can see that a fundamental element is the Object context and its properties. If you expose a Object context without dbset properties, the process used by Migrations is not executed the right way.

I have my solution with the following projects: Core.Entities, Core.RepositoryInterfaces and Infraestructure.RepositoryEF, Infraestructure.DependencyResolution, and UI.WebSite.

As you know the repositories are injected in the class constructor when I need them:

  private IRepository<Product> _productrepo;  
  Public Test(IRepository<Product> productRepo)
  {
            _productRepo = productrepo;
   }

The question is: How can the Migration update the database since my Object context does not have dbset<> properties (my dependency tool inject those repositories in runtime)?

Thanks for your valuable help.


Solution

  • I think code first migrations won’t update your model if you have an empty dbcontext object (I mean without dbset properties). So one way to handle this scenario where you are using the repository pattern and injecting dbcontext objet to every requested repository is:

    Design two dbcontext objects, one for development time (devdbcontext) and the other for production environment (proddbcontext).

    1. Devdbcontext will be designed with dbset properties, this way the migration workflow will be normal in development time; it will detect model changes and will recreate the database, etc. This object will be selected when you are in DEBUG mode (#if DEBUG)

    2. Proddbcontext will be a derived dbcontext object without dbset properties and will be selected when you are in RELEASE mode (#if RELEASE). For updating the production database I will generate a DATABASE SCRIPT and set the database initilializer to NULL.

    What do you think of this solution?