Web Api 2.2 - 类库项目中的代码优先迁移 [英] Web Api 2.2 - Code First Migration in Class Library Project

查看:264
本文介绍了Web Api 2.2 - 类库项目中的代码优先迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在myVS 2015解决方案中有两个项目。


  1. 项目A




    • Web Api 2.2项目

    • 定义DBContext类和连接字符串(在web.config文件中)的主项目


  2. 项目B




    • 类图书馆项目

    • 作为参考添加项目A

    • 模特儿&控制器定义

    • 模型继承一类Project A

    • 创建一个从Project A继承DBContext的DBContext类。

    • public DbSet Planets {get;组; }


我以上项目结构背后的想法是: strong>


  1. 减少项目扩大时的复杂性


  2. 为了减少复杂性,增加可读性


  3. 项目A中的授权逻辑


我必须在项目B中实现以下功能: / p>


  1. 需要从项目A分享/访问连接字符串

  2. 需要运行代码第一次迁移。 / li>
  3. 需要知道如何在将应用程序部署到prod时运行代码第一次迁移?

问题:



我已经启用了代码优先迁移并更新了数据库。
我没有运行任何问题,但它没有运行在项目A的web.config中配置的数据库。相反,它添加了自己的本地数据库。



我应该在项目B中指定连接字符串。如果是,作为其类库,如何添加配置文件?

解决方案

您需要在App中指定连接字符串.Config然后在DbContext的构造函数中给出Connection字符串的名称。这样。

  public ApplicationContext():Base('ConnectionString ')

此外,您还需要将DefaultConnectionFactory从LocalDbConnectionFactory更改为AppConfig中的SQLConnectionDbFactory。 >

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?

解决方案

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.

这篇关于Web Api 2.2 - 类库项目中的代码优先迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆