Asp.net核心 - 没有这样的表:AspNetUsers [英] Asp.net core - no such table: AspNetUsers

查看:183
本文介绍了Asp.net核心 - 没有这样的表:AspNetUsers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图暗示用户登录我的一个asp.net核心应用程序。我遵循微软教程 here 。我有两个上下文,一个叫做SchoolContext,用于保存所有与学校相关的模型,另一个称为ApplicationDbContext的上下文为Account模型。这些都被保存到sqlite数据库。

一切正常,直到我尝试将用户注册到我的上下文。当我尝试注册一个用户,我得到,找不到AspNetUsers表错误。如果我查看数据库,我看不到AspNetUser表。我尝试添加迁移,但我仍然得到相同的错误。为什么表不被创建?

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

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

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

ApplicationUser.cs

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

appsettings.json

appsettings.json

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

错误

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()


推荐答案

听起来像你忘记在包管理器控制台中调用 update-database 。这是您创建的迁移到连接的数据库的实际应用。

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.

要更改用户表名称,您想在 OnModelCreating 方法中的数据库上下文中执行此操作:

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

然后运行一个快速的 update-database ,然后重试。

Then run a quick update-database and try again.

这篇关于Asp.net核心 - 没有这样的表:AspNetUsers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆