问题描述
这是我的代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("AppDbContext"));
});
services.AddMvc();
}
这是我的DbContext:
And this is my DbContext:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Actor> Actors { get; set; }
public DbSet<Movie> Movies { get; set; }
public DbSet<MovieActor> MovieActors { get; set; }
}
我的ConnectionString很好.我真的很想知道为什么运行此代码时我的数据库没有生成?断点在 services.AddDbContext
行中命中,但是当我在 AppDbContext
中放置断点时却没有命中.有人可以帮忙吗?我的代码正是这样的 https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro
And my ConnectionString is just fine. I'm really wondering why my DB is not generating when I run this code? The breakpoint is hitting in the line services.AddDbContext
but when I put a breakpoint in AppDbContext
it is not hitting. Can anybody help? My code exactly is looks like this https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro
推荐答案
这是第一次创建您的Db(下面的代码).但是,迁移与创建不同.您可以检查链接( https://msdn.microsoft.com/en-us/library/jj591621(v = vs.113).aspx ).如果要通过代码管理Db,则应在部署管道中涉及DbMigrations脚本的执行,否则就没有太大用处.
This create your Db for first time (code at below). However, migration is different than creation. You can check link ( https://msdn.microsoft.com/en-us/library/jj591621(v=vs.113).aspx ). If you want to manage Db from your code, DbMigrations scripts execution should be involved your deployment pipeline, otherwise it is not much usefull.
也存在自动迁移(自动检测更改并在db上执行)(实体框架,自动应用迁移).但这并不能提供足够的灵活性,我不建议将其用于生产.
Automatic migration (auto detect changes and executed on db) are also exist (Entity Framework, Automatic apply Migrations). But this does not gives much flexibly and I do not recommend for production.
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
this.Database.EnsureCreated();
}
public DbSet<Actor> Actors { get; set; }
..............
这篇关于EF代码首先不创建数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!