5

So im trying to implment user login for my a asp.net core application. Im following the microsoft tutorial here. I have two contexts, one called SchoolContext for saving all the school related models, and another context called ApplicationDbContext for the Account models. This is all being saved to a sqlite database.
Everything works fine, up until I try to register a user to my context. When I try to register a user i get, cant find AspNetUsers table error. If I look in the database I don’t see the AspNetUser table. I tried adding migrations, but i still get that same error. Why is the table not being created ?

Startup.cs

public class Startup {
        public IConfigurationRoot Configuration { get; }
        public Startup(IHostingEnvironment env) {
            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();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Add Context services
            services.AddDbContext<SchoolContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("MainConnection")));
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("MainConnection")));

            // Add Identify servies 
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
            // Add framework services
            services.AddMvc();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            // Config hot module replacement
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
                    HotModuleReplacement = true
                });
            }
            else {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            // Enabled Identity
            app.UseIdentity();
            // Confgure routes 
            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
            // Initialize school database [FOR TESTING] 
            DbInitializer.Initialize(context);
        }
    }

ApplicationDbContext.cs

namespace ContosoUniversity.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }
}

ApplicationUser.cs

namespace ContosoUniversity.Models
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
    }
}

appsettings.json

  "ConnectionStrings": {
    "MainConnection": "Data Source=/home/Josn/AspNetCore/ContosoUniversity/Databases/database.db"
  },

Error

fail: Microsoft.EntityFrameworkCore.Query.RelationalQueryCompilationContextFactory[1]
      An exception occurred in the database while iterating the results of a query.
      Microsoft.Data.Sqlite.SqliteException: SQLite Error 1: 'no such table: AspNetUsers'.
         at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
         at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
         at Microsoft.Data.Sqlite.SqliteCommand.<ExecuteDbDataReaderAsync>d__53.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__20.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable.AsyncEnumerator.<MoveNext>d__8.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.<_FirstOrDefault>d__82`1.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Query.Internal.TaskResultAsyncEnumerable`1.Enumerator.<MoveNext>d__3.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
AJ_
  • 3,787
  • 10
  • 47
  • 82
  • Not sure if this is resolved: http://stackoverflow.com/questions/22174212/entity-framework-6-with-sqlite-3-code-first-wont-create-tables – Steve Greene Oct 03 '16 at 16:12
  • @SteveGreene I dont think so, the SchoolContext tables are initiated. – AJ_ Oct 03 '16 at 17:04
  • Do you see a [Users] table? In my case I am even able to write to the Users table in one request but the next request tries to read from AspNetUsers – Marc Wittke Oct 25 '16 at 18:43
  • Nevermind, I was missing the call to base.OnModelCreating(builder); – Marc Wittke Oct 25 '16 at 18:53

2 Answers2

6

It sounds like you forgot to call update-database in the package manager console. That's what actually applies the migrations you create to your connected database(s).

The other issue may be with how you updated the table name(s). If you edited the migrations directly, it has no way to know that you changed the name at run-time and will still look for the default named tables.

To change the user table name, you want to do something like this in your DB context in the OnModelCreating method:

protected override void OnModelCreating( ModelBuilder builder ) {
    base.OnModelCreating( builder );
    // Customize the ASP.NET Identity model and override the defaults if needed.
    // For example, you can rename the ASP.NET Identity table names and more.
    // Add your customizations after calling base.OnModelCreating(builder);

    builder.Entity<ApplicationUser>() //Use your application user class here
           .ToTable( "ContosoUsers" ); //Set the table name here
}

You'll then want to create a migration to make sure everything is updated by running the following in the package manager console:

add-migration RenamedUserTable

Then run a quick update-database and try again.

  • 1
    I had to delete the databases and then call update database. Thanks. dotnet ef database update -c ApplicationDbContext – AJ_ Oct 10 '16 at 23:39
  • So this might be my problem, maybe you can help clearify if this is it or not. I changed the Migration table names from AspNetUsers to ContosoUsers. I tried searching in the project to see if AspNetUsers was still being used anywhere, but its not. So i dont know why identity is searching for AspNetUsers instead of ContosoUsers. – AJ_ Oct 11 '16 at 00:05
  • What did you do to change it? – Richard Marskell - Drackir Oct 11 '16 at 02:10
  • Thanks for the replay. I did the migration command, and went into the migration cs files and changed the names in there. The database shows that the names changed. – AJ_ Oct 11 '16 at 02:19
  • I don't think you can do it that way. Then, the model won't know that you've changed the table name. I think you'll have to change it in the db context `OnModelCreating`. See here: http://ef.readthedocs.io/en/latest/modeling/relational/tables.html – Richard Marskell - Drackir Oct 11 '16 at 02:31
  • I dont even know why it searching for AspNetUser. All my dbContext info is in the class listed above. – AJ_ Oct 11 '16 at 03:29
  • I updated my answer to include some more info based on these comments. Hopefully that should resolve it. – Richard Marskell - Drackir Oct 11 '16 at 15:49
  • @John You inherit your context from IdentityDbContext. It contains a DbSet for users. Those users map by default to a table called AspNetUsers. You should not be modifying the migration to something the model doesn't expect. – juunas Oct 11 '16 at 16:58
  • @juunas Oh, now it makes sense. So i have to edit the default idenityDbContext. Okay ill give that a try. Thanks. – AJ_ Oct 11 '16 at 17:50
2

I was getting same issue which I fixed by providing table name in OnModelCreating method.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string SQLLiteConnectionString = @"Data Source=C:/Projects/ArticlesDB.db";
            optionsBuilder.UseSqlite(SQLLiteConnectionString);             
        }
protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Articles>().ToTable("Articles");
            modelBuilder.Entity<Articles>(entity =>
            {
                entity.Property(e => e.Id).IsRequired();
            });
        }
Sumit Bajaj
  • 327
  • 3
  • 3