【问题标题】:Unable to create SQL Table using code first approach in Azure via Entity Framework无法通过实体框架在 Azure 中使用代码优先方法创建 SQL 表
【发布时间】:2018-10-28 17:29:03
【问题描述】:

我正在尝试使用 EF 将我的数据库发布到 azure,但在迁移后看不到任何表。

我尝试了以下命令:

Add-Migration MyTables
Update-Database

当我通过 SSMS 检查我的 Azure DB 时,我可以在 dbo.__EFMigrationsHistory 表中看到所有迁移的日志,但没有创建任何表。

我的上下文类:

 public class ApplicationContext : DbContext
{
    public DbSet<Expense> Expenses { get; set; }

    public ApplicationContext(DbContextOptions opts) : base(opts)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    }
}

连接字符串:

“连接字符串”:{ "ExpenseApplicationDB": "Server=tcp:myserver,1432;Initial Catalog=ExpenseDatabase;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection 超时=30;" }

还在数据库部分的发布对话框中显示“项目中未找到数据库”。

如果我尝试使用本地数据库来实现与预期相同的效果。有什么做错了吗?

【问题讨论】:

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


    【解决方案1】:

    当您使用 .net EntityFramework 发布时,您可以单击选项卡执行代码优先迁移(在应用程序启动时运行)

    但是,在 EF 核心中,它并不存在。另外,EF 不支持自动迁移,您可能需要手动执行Add-Migration 来添加迁移文件。

    还在数据库部分的发布对话框中显示“项目中未找到数据库”。

    你也不能存在数据库,你不能apply migration on publish

    如果你想apply migration at runtime,你可以在Startup.csConfigure方法中添加以下代码。

     using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
        }
    

    更多详情可以参考这个thread

    注意,您需要确保可以连接到 Azure 数据库。您可以将天蓝色的连接设置为 vs 本地。这样您也可以在本地使用 azure 数据库进行测试和调试。

    【讨论】:

    • “您也无法存在数据库,您无法在发布时应用迁移” - 您能否详细解释一下,我的项目类型是“Web API”而不是“Web 应用程序” .
    • 根据您的描述,我只能猜测它是一个 asp.net 核心应用程序。我之前遇到过同样的问题,就像没有数据库显示一样。所以我添加代码实现自动迁移。
    • 您也可以将代码添加到 Startup.cs 中尝试。
    • 试过 myDbContext.Database.Migrate();这在 startup.cs 中,但仍然无法迁移。
    • 其实需要在Startup.cs的Configure方法中添加我提供的第二个代码片段
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    相关资源
    最近更新 更多