代码优先方法不创建表

时间:2018-09-21 10:06:13

标签: c# entity-framework asp.net-core-2.0

我正在Core 2.0中开发应用程序,并使用标识创建表。因此,当我运行应用程序时,数据库会自动创建。稍后,当我尝试运行迁移命令时,它不会创建表。 // DAL

public class ApplicationDbContext:IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
        {

        }
        public DbSet<tblContact> tblContacts { get; set; }

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

//必需的表类

 public partial class tblContact
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ContactId { get; set; }
        public string PhoneNumber { get; set; }
    }

以下是我运行的命令

  • 添加迁移20180921
  • update-database -verbose

在控制台的输出末尾说 错误号:2714,状态:6,类:16 数据库中已经有一个名为“ AspNetRoles”的对象。

另一件事是,当我删除数据库并运行应用程序时,所需表自动创建而无需运行任何命令。 我在这里想念的是什么? 以下是Start.cs文件

public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            var builder = new ConfigurationBuilder()
           .SetBasePath(env.ContentRootPath)
           .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
           .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
           .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddIdentity<ApplicationUser, IdentityRole>()
               .AddEntityFrameworkStores<ApplicationDbContext>()
               .AddDefaultTokenProviders();
            services.ConfigureApplicationCookie(config =>
            {
                // Cookie settings
                config.ExpireTimeSpan = TimeSpan.FromHours(2);
                config.SlidingExpiration = true;
                config.LoginPath = "/Account/Login";
                config.LogoutPath = "/Account/LogOut";
                config.AccessDeniedPath = "/Account/AccessDenied";
            });
            services.AddTransient<IAccountBAL, AccountBAL>();
            services.AddSingleton<IConfiguration>(Configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAccountBAL _iAccountBAL)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            SeedDatabase.Initialize(app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope().ServiceProvider);
            _iAccountBAL.CreateDefaultRoles().Wait();
            _iAccountBAL.CreateSuperAdmin().Wait();
        }
    }


 public static void Initialize(IServiceProvider serviceProvider)
        {
            var context = serviceProvider.GetRequiredService<ApplicationDbContext>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            context.Database.EnsureCreated();
        }

1 个答案:

答案 0 :(得分:0)

听起来像您的应用程序在运行时应用迁移。请检查您的Startup.cs是否已迁移。如果需要应用程序,则需要将其删除,以便从程序包管理器控制台运行迁移。

private static void InitializeMigrations(IApplicationBuilder app)
{
    using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
    {
        MyDbContext dbContext = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
        dbContext.Database.Migrate();

    }
}

来自MSDN

确保上下文数据库存在。如果存在,则不采取任何措施。如果它不存在,那么将创建数据库及其所有架构。如果数据库存在,则不做任何努力来确保它与此上下文的模型兼容。

请注意,此API不使用迁移来创建数据库。此外,创建的数据库以后无法使用迁移进行更新。如果您以关系数据库为目标并使用迁移,则可以使用DbContext.Database.Migrate()方法来确保已创建数据库并应用了所有迁移。