我启动asp core
应用程序时无法创建数据库,即使我之前能够在其他项目上执行此操作。
我的上下文类称为DatabaseContext
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<Person> People { get; set; }
}
DbInitializer.cs
public class DbInitializer
{
public static void Initialize(DatabaseContext context)
{
context.Database.EnsureCreated();
if (context.People.Any())
{
return; // DB has been seeded
}
var people = new Person[]
{
new Person{ FirstName = "John", LastName = "Johnson", Age = 32, Email = "john@gmail.com", Subscribed = true},
new Person{ FirstName = "Bob", LastName = "Bobson", Age = 22, Email = "bob@gmail.com", Subscribed = false},
new Person{ FirstName = "Sally", LastName = "Jackson", Age = 26, Email = "sally@gmail.com", Subscribed = false},
};
foreach (Person p in people)
{
context.People.Add(p);
}
context.SaveChanges();
}
}
appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TESTDB;Trusted_Connection=True;MultipleActiveResultSets=true"
},
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DatabaseContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
Program.cs
public static void Main(string[] args)
{
//BuildWebHost(args).Run();
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<DatabaseContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
}
当我运行应用程序时,我没有在Users
文件夹中创建数据库文件,也没有在SQL Server Object Explorer