Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF code first not creating the database

Here is my code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options =>
    { 
     options.UseSqlServer(Configuration.GetConnectionString("AppDbContext"));
    });

    services.AddMvc();
}

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; }

}

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://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro


1 Answers

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.

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; }
..............
like image 163
Adem Catamak Avatar answered Dec 16 '25 14:12

Adem Catamak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!