【问题标题】:Enable migrations with N-Tier Repository pattern Visual studio project使用 N 层存储库模式 Visual Studio 项目启用迁移
【发布时间】:2015-12-18 07:25:55
【问题描述】:

使用 N 层应用程序。 有存储层、服务层和表示层项目。 只有 Repository Layer 引用了实体框架。 只有表示层(web.config)有配置字符串。 我已经使用IDbContextFactory 和依赖注入来注入配置

如何启用迁移它给出错误

检查上下文是否针对现有数据库...System.ArgumentException:参数“nameOrConnectionString”不能为空、空或仅包含空格。在 System.Data.Entity.Utilities.Check.NotEmpty(String value, String parameterName) 在 System.Data.Entity.DbContext..ctor(String nameOrConnectionString)

正如我提到的,连接字符串(配置)是从表示层注入的,我正在使用 Autofac 进行 DI

这里是存储库层中使用的上下文工厂

 public class MyContextFactory : IDbContextFactory<MyContext>
    {
        public ILogger Logger { get; set; }
        private readonly string _configuration;
        public MyContextFactory(string configuration)
        {
            _configuration = configuration;
        }
        public MyContextFactory()
        {

        }
        public MyContext Create()
        {
            var dbcontext =new MyContext(_configuration, Logger);

            return dbcontext;
        }
    }

【问题讨论】:

  • 你能展示你的代码吗?此错误清楚地表明您忘记传递连接字符串。
  • 代码正在运行,我在没有启用迁移的情况下开发了它...正如我提到的,连接字符串是从表示层注入的,我正在使用 Autofac 进行 DI

标签: c# asp.net .net entity-framework-6 entity-framework-migrations


【解决方案1】:

让它工作 答案是将连接字符串 添加到您的存储库项目的app.config 中。 (只需从web.config复制即可)

当您将 迁移 指向该项目时,我认为它不够聪明,无法知道在哪里查找连接字符串。

【讨论】:

    【解决方案2】:

    经过大量研究(将近 2 天),我得到了解决方案: 在 DbContext 类中添加以下无参数构造函数,并在使用迁移时使 Web 项目成为启动项目(即 PM 控制台中的 enable-migration、add-migration 等命令。)

     #region Needed For migrations
            private static string ConnectionStringForMigration()
            {
                return ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
            }
    
            public MyContext()
                : base(MyContext.ConnectionStringForMigration())
            {
    
            } 
            #endregion
    

    【讨论】:

      猜你喜欢
      • 2014-03-23
      • 2017-07-03
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多