Code first approach does not create table

Viewed 240

I am developing application in Core 2.0 and using identity to create tables. So when I run application the database automatically create. Later when I try to run migration command it does not create table. //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);
        //}
    }

//Required Table Class

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

Following is commands that I ran

  • add-migration 20180921
  • update-database -verbose

At the end of output in console it says Error Number:2714,State:6,Class:16 There is already an object named 'AspNetRoles' in the database.

One more thing that when I drop database and run application then required tables create automatically without running any command. What I am missing here? Following is Start.cs file

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 Answers

Sounds like your application applying migrations when it is running. Please check your Startup.cs has migration. You need to remove it if your application has it in order to run migration from package manager console.

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

    }
}

From MSDN

Ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created. If the database exists, then no effort is made to ensure it is compatible with the model for this context.

Note that this API does not use migrations to create the database. In addition, the database that is created cannot be later updated using migrations. If you are targeting a relational database and using migrations, you can use the DbContext.Database.Migrate() method to ensure the database is created and all migrations are applied.

Related