【问题标题】:Database migration with two context in Asp.Net Core (SQL Server on Docker)在 Asp.Net Core 中具有两个上下文的数据库迁移(Docker 上的 SQL Server)
【发布时间】:2018-03-10 22:39:38
【问题描述】:

我的应用程序中有两个上下文。 一位在WebApi Project -> ApiContext (inherited from IdentityDbContext) 另一个在Infrastructure -> Context

我在 Linux 上为 Docker 引擎 (microsoft/mssql-server-linux) 使用 Microsoft SQL Server 的官方镜像。

我写了一个DbFactory。您可以在下面找到我的代码。

ApiContext:

internal class ApiContext : IdentityDbContext<ApplicationUser>
{
    public ApiContext(DbContextOptions<ApiContext> options) : base(options)
    {
        Database.EnsureDeleted();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

上下文

internal class Context : DbContext
{
    public Context(DbContextOptions<Context> options) : base(options)
    {
        Database.EnsureCreated();
    }

    public DbSet<Reservation> Reservations { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Table>().ToTable("Table");
    }
}

在我的基础设施项目中,正如我所说的 DbFactory

public class DesignTimeDbContextFactory<T> : IDesignTimeDbContextFactory<T>
    where T : DbContext
{
    public T CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        var builder = new DbContextOptionsBuilder<T>();
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        builder.UseSqlServer(connectionString);
        var dbContext = (T)Activator.CreateInstance(
            typeof(T),
            builder.Options);
        return dbContext;
    }
}

internal class ContextDesignTimeDbContextFactory : DesignTimeDbContextFactory<Context>
{
}

在 WebApi 项目中

internal class ApiContextDesignTimeDbContextFactory : DesignTimeDbContextFactory<ApiContext>
{
}

我想使用实体框架核心迁移。 当我跑步时

dotnet ef migrations add InitialCreate

在 ApiProject 中(使用 cmd) 我明白了

找到多个 DbContext。指定使用哪一个。使用 PowerShell 命令的“-Context”参数和“--context” dotnet 命令的参数。

您能否告诉我如何在 Asp.Net Core 2.0 和 EntityFrameworkCore 2 和 docker 上使用两个上下文处理数据库迁移。

【问题讨论】:

    标签: entity-framework docker asp.net-core entity-framework-core database-migration


    【解决方案1】:

    您应该指定使用哪个 DbContext:

    dotnet ef migrations add ArbitraryMigrationName -c YourDbContextName
    

    【讨论】:

    • 那么我应该使用该命令两次,一次用于 ApiContext,一次用于 Context,对吗?
    • 是的,完全一样。
    • 我也有同样的情况。当我运行它时,它说 docker 映像没有 .NET SDK。我应该先将 .NET SDK 安装到我的容器吗?这对我来说似乎有点矫枉过正。
    猜你喜欢
    • 2019-04-11
    • 2021-01-16
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2012-05-31
    • 2022-12-09
    • 2011-02-05
    相关资源
    最近更新 更多