0

I'm having an issue with Entity Framework Core while trying to use the code-first approach.

I want the database to be automatically created when I run the code, but it's not happening.

If I don't create the database beforehand, I get an error stating that the relevant table cannot be found.

Here's my context file:

public class IBKSContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=DataAccess.Contexts.IBKSContext;Trusted_Connection=True;MultipleActiveResultSets=true");
    }

    public DbSet<Api> Apis { get; set; }
    public DbSet<Calibration> Calibrations { get; set; }
    public DbSet<Channel> Channels { get; set; }
    public DbSet<DB12> DB12s { get; set; }
}

NuGet packages installed in my project:

Microsoft.EntityFrameworkCore 7.0.8
Microsoft.EntityFrameworkCore.Design 7.0.8
Microsoft.EntityFrameworkCore.SqlServer 7.0.8
Microsoft.EntityFrameworkCore.Tools 7.0.8

I'd appreciate your help. I'm not sure how to proceed, but I really need to get this working.

Thank you in advance for your responses.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mert Atmaca
  • 63
  • 10

1 Answers1

0

You could call the method context.Database.EnsureCreated() to create the database if it does not exist (see MS documentation).

kaffekopp
  • 2,551
  • 6
  • 13
  • 1
    Negative. The documentation you are linking to contains a big **Warning**: *"`EnsureCreated` and Migrations don't work well together. If you're using Migrations, don't use `EnsureCreated` to initialize the schema."* – Ivan Stoev Aug 17 '23 at 07:43