DbUpdateException error trying to use EF core code first


I have a simple Web API and I am trying to use entity framework core code first, with an external sql server database hosted on AWS RDS. My aim is for EF to create my model database/tables automatically, based on my context and models, the first time I use Swagger to create an object. Although when I try to post an object to my API with Swagger, tables do not get created and instead I get the following error: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid object name 'Users'.

Did I set up EF incorrectly?

Db Context:

namespace FitnessTrackerAPI.Data
    public class FitnessTrackerAPIContext : DbContext
        public FitnessTrackerAPIContext (DbContextOptions<FitnessTrackerAPIContext> options)
            : base(options)

        public DbSet<FitnessTracker.UserData> Users { get; set; }

        public DbSet<FitnessTracker.WorkoutData> Workouts { get; set; }

I also added the following to Startup.cs:

    public void ConfigureServices(IServiceCollection services)
         services.AddDbContext<FitnessTrackerAPIContext>(options =>

    private void InitializeDatabase(IApplicationBuilder app)
         using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
                var context = serviceScope.ServiceProvider.GetRequiredService<FitnessTrackerAPIContext>();

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        //Apply pending migrations

Connection String in appsettings.json: "ConnectionStrings": { "FitnessTrackerAPIContext": "Server=fitnessapi.clxnbxbuoxx1.eu-west-1.rds.amazonaws.com,1433;User ID=XXXXX;Password=XXXXX; Initial Catalog=fitnessapi; Database=fitnessapi; Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"

asked on Stack Overflow Apr 3, 2020 by craig2020

1 Answer


You need to call context.Database.EnsureCreated(); to "ensure" the tables are created. More about this method here.

answered on Stack Overflow Apr 4, 2020 by mxmissile

User contributions licensed under CC BY-SA 3.0