1

I'm trying to generate my database using code-first. When I run the command update-database, I receive that database cannot be null, but I expected that database would be automatically created. Any idea what I am missing?

        services.AddControllers();
    }

    public class SmartSchoolContext : DbContext
    {
        public DbSet<Aluno> Alunos { get; set; }
        public DbSet<Professor> Professores { get; set; }
        public DbSet<Disciplina> Disciplinas { get; set; }
        public DbSet<AlunoDisciplina> AlunosDisciplinas { get; set; }

        public SmartSchoolContext(DbContextOptions options) : base(options)
        {
        }

    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<SmartSchoolContext>(context => context.UseMySQL(Configuration.GetConnectionString("Default")));
    services.AddControllers();
}
4
  • To start with, I cleaned up your post but it appears you didn't paste part of the code at the beginning there. Commented Dec 17, 2020 at 15:16
  • What's the exact command you are running? Are you adding any arguments? Commented Dec 17, 2020 at 15:21
  • Does this answer your question? Not creating database using Migration command Update-Database in ASP.Net Core 2 Commented Dec 17, 2020 at 15:22
  • i run Add-Migration init, then Update-database Commented Dec 17, 2020 at 15:28

1 Answer 1

0

in startup.cs>>ConfigureServices method you have to add

services.AddDbContext<SmartSchoolContext>();

in configure method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext context)
{
   // migrate database changes on startup (includes initial db creation)
        context.Database.Migrate();
   // other logic

}

note:: add and update database using command make sure your database connection is open

Sign up to request clarification or add additional context in comments.

1 Comment

I wouldn't recommend automatically migrating the database in production code. The database login the public-facing application is using should generally not have DDL (data definition language) permissions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.