Web Api 2.2 - Code First Migration in Class Librar

2019-05-30 16:55发布

问题:

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.