实体框架核心 - “更新 - 数据库”无法正常工作

时间:2018-01-28 13:26:22

标签: c# asp.net-core entity-framework-core

在我的解决方案中,我有几个.NET Core 2.0项目:

  • App.DataAccess
  • App.DataAccess.Migrations
  • App.WebApi

===(我想用作迁移程序集)中,我有一个App.DataAccess.Migrations类:

AppDbContextFactory

在同一个项目中,我还有一个namespace App.DataAccess.Migrations { using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using System.IO; public sealed class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext> { public AppDbContextFactory() { Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); } public IConfiguration Configuration { get; } public AppDbContext CreateDbContext(string[] args) { DbContextOptionsBuilder<AppDbContext> builder = new DbContextOptionsBuilder<AppDbContext>(); builder.UseSqlServer( connectionString: Configuration.GetConnectionString("DefaultConnection"), sqlServerOptionsAction: sqlOptions => sqlOptions.MigrationsAssembly(GetType().Namespace)); return new AppDbContext(builder.Options); } } } 文件:

appsettings.json

在我的{ "ConnectionStrings": { "DefaultConnection": "Data Source=.\\SQLEXPRESS;Initial Catalog=MyApp;User ID=sa;Password=SomethingSecret;Trusted_Connection=True;MultipleActiveResultSets=true" } } 项目中,我的App.WebApi课程中包含以下内容:

Startup

在同一个项目中,我还将连接字符串添加到public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(ConfigureDatabaseOptions); services.AddMvc(); } private void ConfigureDatabaseOptions(DbContextOptionsBuilder builder) { builder.UseSqlServer("DefaultConnection", ConfigureSqlServerDatabaseOptions); } private void ConfigureSqlServerDatabaseOptions(SqlServerDbContextOptionsBuilder builder) { builder.MigrationsAssembly(typeof(AppDbContextFactory).Namespace); }

添加迁移有效。

更新数据库会抛出此错误:

  

System.ArgumentException:初始化字符串的格式不是   符合从索引0开始的规范。

为什么?

2 个答案:

答案 0 :(得分:2)

解决了它。我通过&#34; DefaultConnection&#34;作为连接字符串而不是连接字符串名称

private void ConfigureDatabaseOptions(DbContextOptionsBuilder builder)
{
    builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), ConfigureSqlServerDatabaseOptions);
}

答案 1 :(得分:0)

我可以通过以下方式解决问题,为了理解解决方案,我放置了一个虚构的connectionString名称。解决方案

@provide_session()
def set_password(session=None):
    conn = MyHook().get_conn(conn_id)
    conn.set_password(my_password)

    session.add(conn)
    session.commit()