Web Api 2.2 - Code First Migration in Class Library Project

喜欢而已 提交于 2019-12-23 02:41:22

问题


I have two projects in myVS 2015 solution.

  1. Project A

    • Web Api 2.2 Project
    • Main Project where DBContext class and connection string (in web.config file) is defined
  2. Project B

    • Class Library Project
    • Project A added as a reference
    • Models & Controller Defined
    • Models inherits a class of Project A
    • Created a DBContext class which inherits DBContext from Project A.
    • public DbSet Planets { get; set; }

My idea behind the above project structure is:

  1. To reduce the complexity when project grows larger

  2. To make it less complex & increase the readability

  3. To make Authentication & Authorization logic in Project A

I have to achieve following thing in Project B:

  1. Need to share/access connection string from Project A
  2. Need to run code first migration.
  3. Need to know how can I run the code first migration when deploying the application to prod?

Problem:

I have enabled code first migration and updated the DB. I'ts running without any issues but its not running against the database configured in web.config of Project A. Instead, its add its own local database.

Should I specify connection string in Project B as well. If yes, as its a class library how can I add a config file?


回答1:


You need to specify your connection string in App.Config and then give the name of Connection string in Constructor of DbContext Like this.

 public ApplicationContext() : Base('ConnectionString')

Also you need to change your defaultConnectionFactory from LocalDbConnectionFactory to SQLConnectionDbFactory in App.Config.



来源:https://stackoverflow.com/questions/42502790/web-api-2-2-code-first-migration-in-class-library-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!