In meiner Lösung habe ich mehrere .NET Core 2.0-Projekte:
In App.DataAccess.Migrations
(die ich als Migrationsassembly verwenden möchte) habe ich eine AppDbContextFactory
Klasse:
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);
}
}
}
Im selben Projekt habe ich auch eine appsettings.json
Datei:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=.\\SQLEXPRESS;Initial Catalog=MyApp;User ID=sa;Password=SomethingSecret;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
In meinem App.WebApi
Projekt habe ich Folgendes in meiner Startup
Klasse:
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);
}
Im selben Projekt habe ich auch die Verbindungszeichenfolge zu appsettings.json
.
Add-Migration funktioniert.
Update-Datenbank löst diesen Fehler aus:
System.ArgumentException: Das Format der Initialisierungszeichenfolge entspricht nicht der Spezifikation, die bei Index 0 beginnt.
Warum?
Ich habe es gelöst. Ich bin vorbei „DefaultConnection“ als Verbindungszeichenfolge anstelle des Verbindungs string name:
private void ConfigureDatabaseOptions(DbContextOptionsBuilder builder)
{
builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), ConfigureSqlServerDatabaseOptions);
}
Die Art, wie ich das Problem lösen konnte, war folgendermaßen: Um die Lösung zu verstehen, habe ich den Namen eines fiktiven connectionStrings eingegeben. Es ist eine Lösung
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AuthenticDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
services.AddIdentity<AplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AuthenticDBContext>()
.AddDefaultTokenProviders();
services.AddMvc().AddJsonOptions(configureJson);
}