【问题标题】:Why is my Library_Dev database not shown in SQL Server Object Explorer( (localdb)\MSSQLLocalDB )?为什么我的 Library_Dev 数据库未显示在 SQL Server 对象资源管理器( (localdb)\MSSQLLocalDB )中?
【发布时间】:2020-11-23 02:39:59
【问题描述】:

我做的第一件事是去appsettings.json然后我写了那个代码:

"ConnectionStrings": {
        "LibraryConnection": "Server=(localdb)\\MSSQLLocalDB;DataBase=Library_Dev;Trusted_Connection=True;MultipleActiveResultSets=True"
    }

接下来我使用 (using Microsoft.EntityFrameworkCore; (DbContext)) 添加了这个类:

public class LibraryContext : DbContext
{
    public LibraryContext(DbContextOptions options) : base(options) { }

    DbSet<Person> person { get; set; }
}

Person 类有属性但忽略它。

然后我打开Startup.cs并在ConfigureServices方法中添加:

services.AddDbContext<LibraryContext>(
                options => options.UseSqlServer(
                    Configuration.GetConnectionString("LibraryConnection")));

当然我输入了控制台管理包:

add-migration "Initial migration"

但我在 SQL Server 对象资源管理器中看不到 Library_Dev

如果你能帮助我,我将非常感激。

【问题讨论】:

    标签: c# asp.net .net sql-server localdb


    【解决方案1】:

    Add-Migration 只是将迁移添加到您的项目中。 接下来,您需要运行 Update-Database 以应用迁移并搭建实际数据库。

    有关如何运行命令的更多信息,请参见以下链接:

    EF Core Migrations

    【讨论】:

      【解决方案2】:

      startup 中使用此代码,当您运行项目时,数据库将创建:

       public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
       {
            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                  var context = serviceScope.ServiceProvider.GetRequiredService<LibraryContext>();
                  context.Database.Migrate();
            }
            ...
        }
      

      【讨论】:

      • 我会避免在应用程序内部使用 database.migrate(),因为它有一个主要限制,即“您不应该同时运行 Migrate 方法的多个实例”如果您正在运行应用程序的多个实例,可能会出现这种情况。
      • database.migrate() 是为应用程序更新数据库的一种正常方式,但当然不是对所有场景都有用,我也没有说它是适用于所有场景的解决方案,而且在这个问题并没有说他要运行多个实例。
      猜你喜欢
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多